Home > Article > Backend Development > What are the ways to create objects in php
php methods to create objects are: 1. Use [new class name ()] to create; 2. Put the class name in a variable as a string; 3. Use objects to create objects; 4 , Use [new self()] to create; 5. Use [new parent()] to create; 6. Use [new static] to create.
The methods are as follows:
1. Create an object with new class name ()
2. The class name is placed in a variable as a string
(Learning video recommendation: java course)
3. Use an object to create an object, and the object is A new object
4. Use new self(); If there is an inherited class new self() returns an instance of that class in which class
5. Use new parent();
6. Use new static() to return an object of the caller’s class
Code example:
<?php class Demo { public $name = "peter"; public function getName(){ return $this->$name; } public function getObj(){ return new self(); } public function getStaticObj(){ return new static(); } } class Demo1 extends Demo { public function getParent(){ return new parent(); } } echo '<pre/>'; //1.用new 类名()创建一个对象 $obj = new Demo(); //2.将类名以字符串的方式放在一个变量中 $className = 'demo'; $obj1 = new $className(); //3.用对象来创建对象,并且该对象是一个新对象 $obj2 = new $obj(); // $obj2 = $obj 不同的 //4.用new self(); 如果有继承类 new self() 在哪个类中返回的就是哪个类的实例 $obj3 = $obj->getObj(); //5.用new parent(); $obj4 = (new Demo1)->getParent(); //6.用new static() 返回的是调用者的类的对象 $obj5 = $obj->getStaticObj();
Related recommendations: php training
The above is the detailed content of What are the ways to create objects in php. For more information, please follow other related articles on the PHP Chinese website!