PHP数据类型

49 阅读1分钟

数据类型

可以使用var_dump对数据类型进行详细信息的输出,类似Pythontype

var_dump('abc')
string(3) "abc"

也可以使用gettype(),只是单纯对数据类型进行输出

echo gettype('abc');
string

字符串

  • 双引号:将会对回车换行变量等字符进行替换
  • 单引号:在单引号字符串中的变量和特殊字符的转义序列将不会被替换
$name = '张三';
print 'name: $name';
print '<br>';
print "name: $name";
name: $name
name: 张三

  • heredoc:第三种表达字符串的方法是用 heredoc 句法结构:<<<

在该运算符之后要提供一个标识符,然后换行,表示符首尾呼应,可以自定

接下来是字符串 string 本身,最后要用前面定义的标识符作为结束标志

$name = 'abc';
echo <<<EOT
    <b>this is $name</b>
EOT;
this is abc
  • newdoc:和heredoc类似,只是不会自动转义字符串中内容

需要做的就是将<<<结构后的标识符使用单引号包裹

$name = 'abc';
echo <<<'EOT'
    <p>this is $name</p>
EOT;
this is $name

整形

不含小数点,可以定义十进制十六进制(0x16)、八进制(08)

echo 0x12;
echo "<br>";
echo 012;
echo "<br>";
echo 12;
18
10
12

浮点型

带小数点的数

echo 1.5;
1.5

布尔

用以控制条件语句

echo true;
echo false;

数组

PHP 中的 array 实际上是一个有序映射

array(
    key  => value,
    key2 => value2,
    key3 => value3,
)

key 为可选项。如果未指定,PHP 将自动使用之前用过的最大int键名加上 1 作为新的键名

$array = array("foo", "bar", "hello", "world");
array(4) {
  [0]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  [2]=>
  string(5) "hello"
  [3]=>
  string(5) "world"
}

如果从中间的key开始给定

$array = array(
         "a",
         "b",
    6 => "c",
         "d",
);
array(4) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [6]=>
  string(1) "c"
  [7]=>
  string(1) "d"
}

访问数组可以通过中括号,中括号传key

array[key];

对象

对象类似Python的类,使用class语句定义,使用new实例化一个类

对象可以包含属性和方法

class A
{
	function echo_hello()
    {
        echo "hello world";
    }
}
$a = new A;
$a->echo_hello()

对象具有构造函数,可以在构造时像对象传参

class A
{
    private $name;
    public function __construct($name)
    {
        $this->name = $name;
    }
    function echo_hello()
    {
        echo "hello world $this->name";
    }
}
$name = 'abc';
$a = new A($name);
$a->echo_hello();

对象的传入参数一般要在对象中进行预先定义private $name;

空值在PHP中,被称作null

$empty = null;