实例
<?php echo '1. 匿名类中可以使用构造方法<br>'; echo (new class('B') {private $name; public function __construct($name) {$this->name = $name;} public function show($var1){return $this->name.'X'.$var1;} })->show('man'); echo '<hr>'; echo '2. 在匿名类中可以继承其它类中的成员<br>'; class Kongfu { protected $skill; public function __construct($skill='') { $this->skill=$skill; } public function show() { return $this->skill?:'看破斩'; } } echo (new class('阿三','自爆') extends Kongfu { private $name; public function __construct($name,$skill = '') { parent::__construct($skill); $this->name=$name; } public function show() { return $this->name.'的技能是'. parent::show(); } })->show(); echo '<hr>'; echo '3.可以在类声明中嵌套一个匿名类<br>'; class Animal { public $name='谁?'; protected $color='黑'; private $type='中华小当家'; public function demo1 () { return (new class($this->type) extends Animal { private $type; public function __construct($name) { $this->type=$name; } public function demo2() { return '我是嵌套方法'; } public function show($name) { return $this->$name; } }) ; } } //echo (new Animal())->demo1()->demo2(); echo (new Animal())->demo1()->show('type');
运行实例 »
点击 "运行实例" 按钮查看在线实例
实例
<?php class Person { protected $name='王小明'; public function study($skill='php') { return $this->name.'在学习'.$skill; } } Trait Another { public function study($skill='Python') { return $this->name.'在学习'.$skill; } } Trait TheOther { public function study($skill='java') { return $this->name.'在学习'.$skill; } } class Allin extends Person { // use TheOther; // use Another; use TheOther ,Another{ Another::study insteadof TheOther; TheOther::study as my_study; } } $person=new Allin(); echo $person->my_study();
运行实例 »
点击 "运行实例" 按钮查看在线实例
实例
<?php class Mysqli1 { private $db; private $host; private $user; private $password; public function __construct($host,$user,$password) { $this->host=$host; $this->user=$user; $this->password=$password; $this->connect(); } public function connect() { $this->db=mysqli_connect($this->host,$this->user,$this->password); } public function __sleep() { return ['host','user','password']; } public function __wakeup() { $this->connect(); } } $obj= new Mysqli1('localhost','root',''); $tmp=serialize($obj); var_dump( unserialize($tmp));
运行实例 »
点击 "运行实例" 按钮查看在线实例
1. 匿名类中可以使用构造方法
2. 在匿名类中可以继承其它类中的成员
3.可以在类声明中嵌套一个匿名类 (1. 宿主类中的私有成员不能在匿名类中直接使用2. 可以通过在匿名类创建一个构造方法将宿主类中的私有成员进行注入3. 将宿主类中的私有属性做为匿名类的构造方法的参数传入即可)
trait 类位于 Person 与 Student之间,同名方法将父类方法重写
在2个trait 中同名方法用关键字改写 Another::study insteadof TheOther;TheOther::study as my_study;
spl_autoload_register(function($classname)
{
require'./class/'.$classname.'.php';
});类的自动加载
存在命名空间的情况下
$className = str_replace("\\","/", $className); (将命名空间的分隔符替换成目录分隔符)
require './class/'.$className.'.php';
对象序列化的特点:
1. 只保存对象中的属性,不保存方法
2. 只保存类名,不保存对象名