PHP类基础(2)之生成对象的6种方法

<?php 
//生成对象的6种方法
class Demo1{
	public $name = 'PHP中文网';
	public function getName(){
		return $this->name;
	}

	public function getObj(){
		return new self();
	}
	public function getStatic(){
		return new static();
	}
}

class Demo2 extends Demo1
{
	public function getNewObj(){
		return new parent();
	}
}
//1、使用new 类名()  来创建一个对象
$obj = new Demo1();
echo $obj->name;
echo "<hr>";
//2、将类名,以字符串的方式放在一个变量中
$className = 'Demo1';
$obj1 = new $className();
echo $obj1->name;
echo "<hr>";
//3、 用对象来创建对象,并且他创建的是一个新对象
$obj2 = new $obj();//注意:与$obj2 = $obj不同
echo $obj2->name;
echo "<hr>";
//4、用new self()
$obj3 = $obj->getObj();
echo $obj3->name;
echo "<hr>";
//用new parent() 来创建一个对象(基于父类)
$obj4 = (new Demo2)->getNewObj();
echo get_class($obj4);
echo $obj4->name;
echo "<hr>";
//基于当前调用的类来创建:new static
$obj5  = (new Demo2)->getStatic();
$obj6 = (new Demo1)->getObj();
echo get_class($obj5);//基于 new static
//new static 创建的对象,直接与调用者绑定,静态延迟绑定
echo get_class($obj6);//基于 new self
echo $obj5->name;
echo $obj6->name;
 ?>
上一篇:python 包


下一篇:node.js解决 Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol request