6 ways to create objects in PHP

王林
Release: 2023-04-07 19:08:01
Original
6530 people have browsed it

6 ways to create objects in PHP

Create object instance:

<?php
/**
 * PHP创建对象的六种方式
 */
class Person{
  private $name = &#39;bruce&#39;;
  public function getName(){
    return $this->name;
  }
  public static function getObjBySelf(){
    return new self();
  }
  //动态延迟绑定,能识别调用者
  public static function getObjcByStatic(){
    return new static();
  }
}
//Person子类 Teacher
class Teacher extends Person{
  public static function getObjByParent(){
    return new parent();
  }
}

//1、new 类名();创建对象
$obj1 = new Person();//等价于写法 $obj1 = new Person;
echo &#39;类名:&#39;.get_class($obj1).&#39;<br>&#39;;
echo $obj1->getName().&#39;<hr>&#39;;

//2、将类名字符串赋值给一个变量,通过变量创建
$clsName = &#39;Person&#39;;
$obj2 = new $clsName();
echo &#39;类名:&#39;.get_class($obj2).&#39;<br>&#39;;
echo $obj2->getName().&#39;<hr>&#39;;

//3、通过对象实例创建对象
$obj3 = new $obj2();
echo &#39;类名:&#39;.get_class($obj3).&#39;<br>&#39;;
echo $obj3->getName().&#39;<hr>&#39;;

//4、通过 new self()
//$obj4 = (new $obj3())->getObjBySelf();
$obj4 = Person::getObjBySelf();
echo &#39;类名:&#39;.get_class($obj4).&#39;<br>&#39;;
echo $obj4->getName().&#39;<hr>&#39;;

//5、通过 new parent()
$obj5= Teacher::getObjByParent();
echo &#39;类名:&#39;.get_class($obj5).&#39;<br>&#39;;
echo $obj5->getName().&#39;<hr>&#39;;

//6、通过 new static();
$obj6 = Person::getObjcByStatic();
echo &#39;类名:&#39;.get_class($obj6).&#39;<br>&#39;;//类名:Person
echo $obj6->getName().&#39;<hr>&#39;; //bruce
//当用子类去调用时候,发现static自动识别当前调用者(静态延迟绑定),返回当前调用者对象
$obj7 = Teacher::getObjcByStatic();
echo &#39;类名:&#39;.get_class($obj7).&#39;<br>&#39;;//类名:Teacher
echo $obj7->getName().&#39;<hr>&#39;;//bruce
$obj8 = Person::getObjBySelf();
echo &#39;类名:&#39;.get_class($obj8).&#39;<br>&#39;;//类名:Person
echo $obj8->getName().&#39;<hr>&#39;;
//new self()在子类中调用依旧返回原来父类的绑定
$obj9 = Teacher::getObjBySelf();
echo &#39;类名:&#39;.get_class($obj9).&#39;<br>&#39;;//类名:Person
echo $obj9->getName().&#39;<hr>&#39;;
Copy after login

Run result:

6 ways to create objects in PHP

Recommended tutorial: PHP video tutorial

The above is the detailed content of 6 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!