What are the ways to create objects in php

王林
Release: 2023-03-07 15:16:01
Original
3304 people have browsed it

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.

What are the ways to create objects in php

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 &#39;<pre/>&#39;;
//1.用new 类名()创建一个对象
$obj = new Demo();
//2.将类名以字符串的方式放在一个变量中
$className = &#39;demo&#39;;
$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();
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!