Blogger Information
Blog 5
fans 0
comment 0
visits 10646
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
php创建对象的六种方式
勇往直前
Original
7241 people have browsed it

实例

<?php
class Demo
{
	//public private protected对象访问控制符
	//->对象访问运算符
	public $name='php中文网';
	
	public function getName()
	{
		return $this->name;
	}

	public static function getSelf()
	{
		return new self();
	}

	public function getStatic()
	{
		return new static();
	}
}
class Demo2 extends Demo
{
	public function getParent()
	{
		return new parent();
	}
}
//对象访问的六种方式
//1.用 new 类名()来创建一个对象
$obj1 = new Demo();
echo $obj1->name,'<hr>';
//2.将类名以字符串的方式放在一个变量中
$className = 'Demo';
$obj2 = new $className();

echo $obj2->name,'<hr>';
//3.用对象来创建对象,并且它创建的是一个新对象
$obj3 = new $obj2();
echo $obj3->name,'<hr>';
//4.在类中创建一个对象 new self()
$obj4 = Demo::getSelf();

echo $obj4->name,get_class($obj4),'<hr>';

//5.在子类中 new parent()
$demo2 = new Demo2();
$obj5 = $demo2->getParent();
echo $obj5->name,'<hr>';

//6.实例化子类,通过子类调用父类的方法,父类的方法写new static()
$obj6 = $demo2->getStatic();
echo $obj6->name,get_class($obj6);
?>

运行实例 »

点击 "运行实例" 按钮查看在线实例


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post