其它类型转换为对象

stdClass是PHP的预定义类(Predefined Class), 当在将其它类型转换为对象时就会创建一个stdClass对象。如示例1所示:

示例1

$arr = array('China', 'America', 'Australia');
$arr = (Object) $arr;

$arr2 = array('country'=>'China', 'City'=>'Guangzhou');
$arr2 = (Object) $arr2;

$url = 'http://tangobean.com/';
$url = (Object) $url;

$age = 23;
$age = (Object) $age;

var_dump($arr, $arr2, $url, $age);

示例1输出如下图所示:

动态属性

stdClass和其它类都可以动态添加属性,以在定义类的时间即不用声明属性也不用__set方法,而是在创建了对象之后添加属性,如示例2所示:

示例2

class User {
    public function getName() {
        return $this->name;
    }
}

$obj = new StdClass;
$obj->name = 'James Tang';
$obj->email = '[email protected]';

$user = new User;

//这里将会出现Undefined Notice, 因为name还没有定义
echo 'Name: ' . $user->getName();

$user->name = 'Peter Chen';
$user->email = '[email protected]';

//这里将输出Name:Peter Chen
echo 'Name: ' . $user->getName();

var_dump($obj, $user);

示例2输出如下:

Reference: http://php.net/manual/en/reserved.classes.php