PHP的对象模型是指在PHP中,使用对象来描述现实世界中的事物,实现面向对象编程的一种机制。
在PHP中,每个对象都是一个类的实例,类是一种抽象的数据类型,用于定义对象的属性和方法。类可以看做是对象的模板,对象则是类的具体实现。
在PHP中,可以使用class
关键字来定义一个类:
class MyClass {
// 类的属性
public $property1 = 'hello';
protected $property2 = 'world';
private $property3 = '!';
// 类的方法
public function method1() {
return $this->property1 . $this->property2 . $this->property3;
}
protected function method2() {
return 'protected method';
}
private function method3() {
return 'private method';
}
}
上面的代码定义了一个名为MyClass
的类,该类有三个属性和三个方法,分别为$property1
、$property2
、$property3
和method1()
、method2()
、method3()
。
其中,$property1
是公共属性,可以在类的外部直接访问,$property2
是受保护的属性,只能在类的内部及其子类中访问,$property3
是私有属性,只能在类的内部访问。
类的方法也有相应的访问权限,可以是公共的、受保护的或私有的,访问权限的设置使用public
、protected
、private
关键字。
在PHP中,可以使用new
关键字创建一个对象:
$obj = new MyClass();
上面的代码创建了一个MyClass
类的对象,并将其赋值给$obj
变量。
对象的属性和方法可以通过->
操作符来访问:
echo $obj->property1; // 输出'hello'
echo $obj->method1(); // 输出'hello world!'
上面的代码分别访问了$obj
对象的property1
属性和method1()
方法。
需要注意的是,如果访问的属性或方法是受保护的或私有的,需要在类的内部或其子类中访问,否则会抛出错误。
在PHP中,可以使用extends
关键字实现类的继承:
class MyChildClass extends MyClass {
// 子类的方法
public function method4() {
return $this->method2();
}
}
上面的代码定义了一个名为MyChildClass
的子类,继承了MyClass
类的属性和方法,并新增了一个method4()
方法。
在子类中,可以通过parent::
关键字调用父类的属性和方法:
class MyChildClass extends MyClass {
// 子类的方法
public function method4() {
return parent::method2();
}
}
上面的代码中,method4()
方法调用了父类的method2()
方法。
多态是面向对象编程的一个重要特性,它允许不同的对象对同一消息做出不同的响应。在PHP中,可以通过接口实现多态:
interface MyInterface {
public function method5();
}
class MyChildClass extends MyClass implements MyInterface {
// 子类的方法
public function method5() {
return 'implemented interface method';
}
}
上面的代码定义了一个名为MyInterface
的接口,并让MyChildClass
类同时继承MyClass
类并实现MyInterface
接口。
这样,MyChildClass
类就具有了method1()
、method2()
、method3()
、method4()
和method5()
五个方法。其中method5()
方法是实现了MyInterface
接口的方法。