面向对象的程序设计(英语:Object-oriented programming,缩写:OOP),可以减少代码的冗余,灵活性高,而且可以将代码的可重用性发挥到极致,这篇我们老说一说php面对对象
感觉php的面向对象和java中有点像
PHP 构造函数
- 主要用来在创建对象时初始化对象, 即为对象成员变量赋初始值
在python中的构造函数是__init__ ( self [,args...] )
在php中是__construct ([ mixed $args [, $... ]] ) : void
举一个简单的例子:
<?php
class animal{
public $name;
public $color;
function __construct($par1,$par2){
$this->name=$par1;
$this->color=$par2;
}
function run(){
echo 'there is a '.$this->color.' '.$this->name.' running';
}
}
$dog=new animal('dog','white');
$dog->run();
?>
运行结果:there is a white dog running
php 析构函数
语法:void __destruct ( void )
- 析构函数(destructor) 与构造函数相反,当对象结束其生命周期时(例如对象所在的函数已调用完毕),系统自动执行析构函数。
例如:
<?php
class animal{
public $name;
public $color;
function __construct($par1,$par2){
$this->name=$par1;
$this->color=$par2;
}
function run(){
echo 'there is a '.$this->color.' '.$this->name.' running</br>';
}
function __destruct()
{
echo 'the '.$this->color.' '.$this->name.' stopped running';
}
}
$dog=new animal('dog','white');
$dog->run();
?>
执行结果:
接口
- 接口定义了实现某种服务的一般规范
- 接口是方法的抽象
- 通过关键词
interface
来定义,和定义标准类一样,但里面的方法为空 - 接口中不定义类成员
- 接口中定义的方法都是公有的(特性)
- 实现接口用
implements
操作符 - 类中必须实现接口的所有方法
- 一个类中可以实现多个方法
- 可以间接的使用接口进行多继承(其实不再叫做“继承”了,而是称为“实现”implements)
抽象类
- 在一个类中,如果有至少一个方法是抽象的,那么这个类必须声明为抽象的,抽象类中的方法中没有大括号
- 抽象方法不可以定义为私有
- 被定义为抽象的类不能实例化,它的意义在于被扩展
- 子类方法可以包含父类抽象方法中不存在的可选参数。
- 抽象类可以实现接口,且可以不实现其中的方法
- 不能重写抽象父类的抽象方法
PHP抽象类应用的定义:
abstract class ClassName{}
抽象类与接口的区别
抽象类一般用来定义一类实体是什么,他包含了属性,抽象方法和非抽象方法。接口用来定义一类实体能做什么,一般认为他只有抽象方法,常量极少用到。
Static 关键字
- 声明后的类属性或方法为 static后,就可以不实例化类而直接访问。
- 静态方法中不能使用伪变量
$this
- 静态属性不能由对象通过
->
操作符来访问 - 使用
::
调用类中的静态方法或者常量,属性
修改一下前面的例子:
<?php
class animal{
public static $name = 'dog';
public static $color = 'white';
public function run(){
return 'there is a '.self::$color.' '.self::$name.' running</br>';
}
}
//不实例化类而直接访问
echo 'there is a '.animal::$color.' '.animal::$name.' running</br>';
$foo=new animal();
echo $foo->run();
?>
输入结果:
Final 关键字
- 如果父类中的方法被声明为
final
,则子类无法覆盖该方法 - 如果一个类被声明为
final
,则不能被继承