PHP学习

Array 数组


PHP 中的数组实际上是一个有序映射。映射是一种把 values 关联到 keys 的类型。此类型在很多方面做了优化,因此可以把它当成真正的数组,或列表(向量),散列表(是映射的一种实现),字典,集合,栈,队列以及更多可能性。由于数组元素的值也可以是另一个数组,树形结构和多维数组也是允许的。

Example #1 一个简单数组

<?php
$array = array(
  "foo" => "bar",
  "bar" => "foo",
);
// 自 PHP 5.4 起
$array = [
  "foo" => "bar",
  "bar" => "foo",
];
?>

key 可以是 integer 或者 string。value 可以是任意类型。最后一个数组单元之后的逗号可以省略。通常用于单行数组定义中,例如常用 array(1, 2) 而不是 array(1, 2, )。对多行数组定义通常保留最后一个逗号,这样要添加一个新单元时更方便。

Example #2 仅对部分单元指定键名

<?php
$array = array(
         "a",
         "b",
    6 => "c",
         "d",
);
var_dump($array);
?>


以上例程会输出:


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

   

Object 对象


要创建一个新的对象 object,使用 new 语句实例化一个类:

<?php
class foo
{
    function do_foo()
    {
        echo "Doing foo."; 
    }
}
$bar = new foo;//$bar是新创建的对象
$bar->do_foo();
?>

Callback / Callable 类型


自 PHP 5.4 起可用 callable 类型指定回调类型 callback。

一些函数如 call_user_func() 或 usort() 可以接受用户自定义的回调函数作为参数。回调函数不止可以是简单函数,还可以是对象的方法,包括静态类方法。

Example #1 回调函数示例

<?php 
// An example callback function
function my_callback_function() {
    echo 'hello world!';
}
// An example callback method
class MyClass {
    static function myCallbackMethod() {
        echo 'Hello World!';
    }
}
// Type 1: Simple callback
call_user_func('my_callback_function'); 
// Type 2: Static class method call
call_user_func(array('MyClass', 'myCallbackMethod')); 
// Type 3: Object method call
$obj = new MyClass();
call_user_func(array($obj, 'myCallbackMethod'));
// Type 4: Static class method call (As of PHP 5.2.3)
call_user_func('MyClass::myCallbackMethod');
// Type 5: Relative static class method call (As of PHP 5.3.0)
class A {
    public static function who() {
        echo "A\n";
    }
}
class B extends A {
    public static function who() {
        echo "B\n";
    }
}
call_user_func(array('B', 'parent::who')); // A
// Type 6: Objects implementing __invoke can be used as callables (since PHP 5.3)
class C {
    public function __invoke($name) {
        echo 'Hello ', $name, "\n";
    }
}
$c = new C();
call_user_func($c, 'PHP!');
?>