匿名对象与匿名类的实现过程
实例
<?php header("Content-Type:text/html;charset=utf-8"); class User { public $name; public $age; public function __construct($name,$age) { $this->name = $name; $this->age = $age; } public function export() { return $this->name.$this->age; } } //匿名对象 echo (new User('Yyk',19))->export(); //匿名类 echo (new class('YHH',18) { public $name; public $age; public function __construct($name,$age) { $this->name = $name; $this->age = $age; } public function export() { return $this->name.$this->age; } })->export(); ?>
运行实例 »
Trait类的声明与工作原理
实例
<?php header("Content-Type:text/html;charset=utf-8"); class Dad { public $name; public function __construct($name='Yyk') { $this->name = $name; } public function study($course='PHP') { return $this->name.'在学习'.$course; } } trait One { public $friend; public function study($course='JAVA') { return $this->name.'和'.$this->friend.'在学习'.$course; } } trait Two { public $friend; public function study($course='JAVA') { return $this->name.'和'.$this->friend.'在学习'.$course; } } class Son extends Dad { use One; use Two; use One,Two{ One::study insteadof Two; Two::study as studys; } } $person = new Son(); echo $person->studys();
运行实例 »
类的自动加载函数的写法
实例
<?php header("Content-Type:text/html;charset=utf-8"); spl_autoload_register(function ($classname){ require './class'.$classname.'.php'; }); ?>
运行实例 »
对象的序列化与反序列化的原理与应用;
实例
<?php header("Content-Type:text/html;charset=utf-8"); class Db { private $db = null; private $host; private $user; private $pass; public function __construct($host='127.0.0.1',$user='root',$pass='root') { $this->host = $host; $this->user = $user; $this->pass = $pass; $this->connect(); } public function connect() { $this->db = mysqli_connect($this->host,$this->user,$this->pass); } public function __sleep() { return ['host','user','pass']; } public function __wakeup() { $this->connect(); } } $db = new Db(); $tmp = serialize($db); var_dump(unserialize($$tmp)); ?>
运行实例 »
点击 "运行实例" 按钮查看在线实例
关于面向对象编程,即OOP,它是一种编程范式,满足面向对象编程的语言,一般会提供类、 封装、继承等语法和概念来辅助我们进行面向对象编程。
面向对象是基于万物皆对象这个哲学观点. 所谓的面向对象就是将我们的程序模块化, 对象化,把具体事物的特性属性和通过这些属性来实现一些动作的具体方法放到一个类 里面
面向对象的三大特征 继承,封装,多态
继承:子类可以继承父类,继承父类的属性及方法,使得代码模块化,提高代码复用性
封装:将事物的属性及行为抽象成一个类,代码模块化,提高代码复用性;
多态:为了实现接口重用,是面向对象的最重要的一部分.