本文实例讲述了php反射学习之不用new方法实例化类操作。分享给大家供大家参考,具体如下:
上一篇php反射入门示例简单介绍了 php 反射的几个常见类的使用方法,但是用反射能做些什么,你可能还是想象不到,
下面我稍微应用反射类来做点东西,大家知道实例化一个类需要用new 关键字,不用 new 可以吗?答案是可以的,用反射就能实现:
首先创建一个文件 student.php:
<?php
class Student
{
public $id;
public $name;
public function __construct($id,$name)
{
$this->id = $id;
$this->name = $name;
}
public function study()
{
echo $this->name.' is learning.....'.PHP_EOL;
}
public function showBag(){
echo "My bag have ".$this->bag->all();
}
}
<?php
class Bag{
public function name(){
return "学生包".PHP_EOL;
}
}
class Student
{
public $id;
public $name;
public function __construct($id, $name="xxx", Bag $bag)
{
$this->id = $id;
$this->name = $name;
$this->bag = $bag;
}
public function study()
{
echo $this->name.' is learning.....'.PHP_EOL;
}
public function showBag(){
echo "My bag is ".$this->bag->name();
}
}