在PHP中数据类型分为四大类:
1、基本类型:常见的有int、float、string、boolean
2、复合类型:数组、对象
3、特殊类型: null, 资源
4、回调类型: callback
下面分别讲解一下各类型和简单的实例代码。
1、基本类型:常见的有int、float、string、boolean
// int / float
$age = 30;
$price = 99.66;
// string
$username = 'admin';
// boolean
$isDel = true;
2、复合类型:数组、对象
// 数组
$arr = [30, 99.66, 'admin', true, function () {
}, [1, 2, 3]];
// 对象
$obj = new class(123456)
{
private $salary;
public function __construct($salary)
{
$this->salary = $salary;
}
// 访问器
public function __get($name)
{
return $this->salary;
}
};
echo gettype($obj);
echo "<br>";
echo '工资是: ', $obj->salary;
输出结果为
object
工资是: 123456
3. 特殊类型: null, 资源
在三种情况下对象是null类型:1. 本身是null, 2.没赋值, 3. unset()删除了一个变量
$x = 123;
unset($x);
if (is_null($x)) echo 'NULL';
echo '<br>';
$f = fopen('readme.txt', 'r');
echo gettype($f);
输出结果为
Notice: Undefined variable: x in D:\phpEnv\www\php_vip\0419\demo1.php on line 44
NULL
resource
4. 回调类型: callback
1.php用字符串传递函数, 所以可以用任何方式来引用或传递函数,当成值/数据类型
2.回调的表现形式, 不仅仅"函数, 对象方法, 类方法"
3.接受回调为参数的函数或方法很多, array_filter
function hello(string $name): string
{
return 'Hello ' . $name;
}
echo hello('孙悟空'), '<br>';
// 回调的方式来调用函数, 同步
echo call_user_func('hello', '孙悟空');
echo '<hr>';
// 函数做为对象方法
class Demo1
{
public function hello(string $name): string
{
return 'Hello ' . $name;
}
}
// 'hello'是对象方法,用对象访问
// echo call_user_func([对象,方法], '唐僧');
echo call_user_func([(new Demo1), 'hello'], '唐僧');
echo '<hr>';
// 类方法
class Demo2
{
public static function hello(string $name): string
{
return 'Hello ' . $name;
}
}
echo call_user_func(['Demo2', 'hello'], '猪八戒');
输出结果
Hello 孙悟空
Hello 孙悟空
Hello 唐僧
Hello 猪八戒
评论 (0)