PHP Velho Oeste 2024

简介

PHP 中的每个表达式都属于以下某个内置类型,具体取决于值:

PHP 是动态类型语言,这意味着默认不需要指定变量的类型,因为会在运行时确定。然而,可以通过使用类型声明对语言的一些方面进行类型静态化。

类型限制了可以对其执行的操作。然而,如果使用的表达式/变量不支持该操作,PHP 将尝试将该值类型转换为操作支持的类型。此过程取决于使用该值的上下文。更多信息参阅类型转换

小技巧

类型比较表也很有用,因为存在不同类型之间的值的各种比较示例。

注意: 使用类型转换,强制将表达式的值转换为某种类型。还可以使用 settype() 函数就地对变量进行类型转换。

使用 var_dump() 函数检查表达式的值和类型。使用 get_debug_type() 检索表达式的值和类型。使用 is_type 检查表达式是否属于某种类型。

$a_bool = true; // a bool
$a_str = "foo"; // a string
$a_str2 = 'foo'; // a string
$an_int = 12; // an int
echo get_debug_type($a_bool), "\n";
echo get_debug_type($a_str), "\n";

// 如果是整型,就加上 4
if (is_int($an_int)) {
$an_int += 4;
}
var_dump($an_int);

// 如果 $a_bool 是字符串,就打印出来
if (is_string($a_bool)) {
echo "String: $a_bool";
}
?>

以上示例在 PHP 8 中的输出:

bool
string
int(16)

注意: PHP 8.0.0 之前,get_debug_type() 无效,可以使用 gettype() 函数代替。但是没有使用规范的类型名称。

add a note add a note

User Contributed Notes 1 note

up
0
kuzawinski dot marcin_NOSPAM at gmail dot com
3 years ago
No, despite description here a `callable` still is not a a full-fledged primitive type in PHP.

<?php

function testFunc() { }

class
testClass {
   
    public function
__invole() { }
   
    public static function
testStaticMethod() { }
   
    public function
testMethod() { }
}

$o = new testClass();
$lambda = function() { };

$c1 = 'testFunc';
$c2 = ['testClass', 'testStaticMethod'];
$c3 = [$o, 'testMethod'];
$c4 = $lambda;
$c5 = $o;

var_dump(is_callable($c1));  // TRUE
var_dump(is_callable($c2));  // TRUE
var_dump(is_callable($c3));  // TRUE
var_dump(is_callable($c4));  // TRUE
var_dump(is_callable($c5));  // TRUE

var_dump(gettype($c1)); // string(6) "string"
var_dump(gettype($c2)); // string(5) "array"
var_dump(gettype($c3)); // string(5) "array"
var_dump(gettype($c4)); // string(6) "object"
var_dump(gettype($c5)); // string(6) "object"

?>
To Top