Home >Backend Development >PHP Tutorial >6 ways to create objects in PHP

6 ways to create objects in PHP

王林
王林Original
2019-11-08 17:55:326630browse

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;;

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!

Statement:
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