1.使用stdClass 创建对象
$obj= new stdClass();
$obj->name='zhangsan';
$obj->age=30;
var_dump($obj);
echo '<hr/>';
D:\phpstudy_pro\WWW\test\index.php:6: class stdClass#1 (2) { public $name => string(8) "zhangsan" public $age => int(30) }
2.创建类对象,再new对象
class student
{
public $name='张三';
private $age=20;
public function play()
{
return $this->name . '在玩'.'TA今年'.$this->age;
}
}
$obj1=new student();
var_dump($obj1);
echo '<hr/>';
var_dump($obj1->play());
echo '<hr/>';
D:\phpstudy_pro\WWW\test\index.php:24: class student#2 (2) { public $name => string(6) "张三" private $age => int(20) }
3.将类名以字符串的方式放在一个变量中,再new创建对象
$className='student';
$obj2=new $className();
var_dump($obj2->play());
echo '<hr/>';
D:\phpstudy_pro\WWW\test\index.php:33: string(22) "张三在玩TA今年20"
4将空数组强转为对象
$obj3= (object)[];
$obj3->name='李四';
var_dump($obj3);
echo '<hr/>';
var_dump($obj3->name);
echo '<hr/>';
D:\phpstudy_pro\WWW\test\index.php:39: class stdClass#4 (1) { public $name => string(6) "李四" }
D:\phpstudy_pro\WWW\test\index.php:41: string(6) "李四"