php实现继承
PHP 实现继承的方法
在 PHP 中,继承是通过 extends 关键字实现的,允许子类继承父类的属性和方法。以下是实现继承的具体方式:
基本语法
子类通过 extends 关键字继承父类。父类的非私有属性和方法会自动被子类继承。

class ParentClass {
public $property = '父类属性';
public function method() {
return '父类方法';
}
}
class ChildClass extends ParentClass {
// 子类可以添加自己的属性和方法
public function childMethod() {
return '子类方法';
}
}
$child = new ChildClass();
echo $child->property; // 输出:父类属性
echo $child->method(); // 输出:父类方法
方法重写
子类可以重写父类的方法以实现不同的功能。使用 parent:: 可以调用父类的原始方法。

class ParentClass {
public function method() {
return '父类方法';
}
}
class ChildClass extends ParentClass {
public function method() {
return '重写后的方法,原方法:' . parent::method();
}
}
$child = new ChildClass();
echo $child->method(); // 输出:重写后的方法,原方法:父类方法
访问控制
public:属性和方法可以在任何地方访问。protected:属性和方法只能在类内部或子类中访问。private:属性和方法只能在定义它们的类中访问。
class ParentClass {
protected $protectedProperty = '受保护属性';
private $privateProperty = '私有属性';
protected function protectedMethod() {
return '受保护方法';
}
}
class ChildClass extends ParentClass {
public function accessProtected() {
return $this->protectedProperty . ' - ' . $this->protectedMethod();
}
}
$child = new ChildClass();
echo $child->accessProtected(); // 输出:受保护属性 - 受保护方法
// echo $child->privateProperty; // 错误:无法访问私有属性
构造方法继承
子类可以继承父类的构造方法。如果子类没有定义构造方法,会自动调用父类的构造方法。
class ParentClass {
public function __construct() {
echo '父类构造方法';
}
}
class ChildClass extends ParentClass {
// 未定义构造方法,自动调用父类的构造方法
}
$child = new ChildClass(); // 输出:父类构造方法
如果子类定义了构造方法,需要显式调用父类的构造方法(如果需要)。
class ParentClass {
public function __construct() {
echo '父类构造方法';
}
}
class ChildClass extends ParentClass {
public function __construct() {
parent::__construct();
echo '子类构造方法';
}
}
$child = new ChildClass(); // 输出:父类构造方法子类构造方法
通过以上方法,可以灵活地在 PHP 中实现继承功能。






