Home > Backend Development > PHP Tutorial > Type conversion in php, detailed explanation of examples of system constants/constants/magic constants

Type conversion in php, detailed explanation of examples of system constants/constants/magic constants

黄舟
Release: 2023-03-16 20:02:02
Original
1380 people have browsed it

Type conversion, constants, system constants,Magic constants in PHP

##1.Automatic type conversion;

在运算和判断时,会进行自动类型转换;
1)其他类型转为bool,判断时转换;
  1)整型转布尔型:0转false,非0转为true;
  2) 空字符串和‘0'(“0”)转为false,其他转为true;
  3) 空数组转为false, 非空数组则转为true;
  4) null转为false
  5) 资源打开不成功为false 
    是0或空,打开不成功的转为‘false','0';
2)其他类型转为字符串(字符串拼接);
  null bool int float
  1) null转换为空串(空串不显示)
  2)整数直接转换为对应字符串 5=>'5';
  3)实数直接转换为对应的字符串,但尾0不转(实数小数点最后的0);
  4)true转换为'1‘,false转为空串;
字符串、布尔、整型、浮点、null
3) 运算时发生的类型转换
  1)true/false转换1/0;
  2)null转换为0;
  3)字符串开头的部分的数值换为对应数值;
  4)字符串开头没数值则直接转为0;
  (null,string,bool) < int < float
Copy after login

2. Forced type conversion

就是手动的把一个类型的值转换为另一个类型的值;
  1、类型转化函数 intval ,strval, floatval
    $num1 = 1.2;
    $num2 = strval($num1); //吧$num1的值转换为字符串;
    var_dump($num1); 
    var_dump($num2); 
  2、(类型)$变量  不能转为resource
    $num2 = (unset)$num2;转为空
  3、settype(变量,类型) 类型必须写成字符串;
    改变变量的类型和值;
  注意事项
    1)浮点数转整数,直接干掉小数;
    2) echo(int)($num1 + 0.5); 四舍五入
Copy after login

3.Constant

1)常量定义
  define(常量名,常量值)
  define(‘SONG&#39;,22);
注意:
  1)常量名是字符串;
  2)常量值必须是标量
  3)常量名一般大写,和变量做区别;
  4)常量名和变量名,命名规则相同;
2)系统常量
  LINE 当前行号
  FILE 当前文件的名称
  DIR 当前文件的目录;
  PHP_OS  操作系统
  PHP_VERSION php的版本

魔术常量:
FUNCTION 函数名
FUNCTION函数名;
CLASS 类名
CLASS 类名
METHOD方法名
METHOD方法民
NAMESPACE :名空间
NAMESPACE 名空间;
3)常量判断
  defined(常量名) 常量名必须是字符串;
  判断是否定义过常量;
Copy after login

4.Operators and expressions;

1)算数运算符 + - (乘法) /(除法) % .
%求模/取余
0 % 3 = 0
12 % 10 = 2
5 % 19 = 4
1 % 3 = 1;
2 % 3 = 2;
3 % 3 = 0;
-9 % 4 = -1
9 % -4 = 1;
模运算的结果的符号取决于第一个数。
判断奇偶
X%2 == 0 为偶数,能整除
X%2 != 0 则为奇数,不能整除
2 * 3 = 8
指数运算;
2 3 = 8;
3 2 = 9;
Copy after login

The above is the detailed content of Type conversion in php, detailed explanation of examples of system constants/constants/magic constants. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template