小熊奶糖(BearCandy)
小熊奶糖(BearCandy)
发布于 2024-03-12 / 12 阅读
0
0

php面向对象 parent::调用父类中的方法和对象

在PHP中,parent:: 用于在子类中引用父类的方法和属性。以下是一些使用 parent:: 调用父类中方法和变量的例子:

示例1:调用父类的非静态方法

class Animal
{
    public function makeSound()
    {
        echo "The animal makes a sound.";
    }
}

class Dog extends Animal
{
    public function makeSound()
    {
        // 在Dog类中调用父类Animal的makeSound方法
        parent::makeSound();
        echo " The dog barks!";
    }
}

$dog = new Dog();
$dog->makeSound(); // 输出: The animal makes a sound. The dog barks!

示例2:调用父类的构造函数

class Person
{
    protected $name;

    public function __construct($name)
    {
        $this->name = $name;
    }
}

class Employee extends Person
{
    private $position;

    public function __construct($name, $position)
    {
        // 在Employee类的构造函数中调用父类Person的构造函数
        parent::__construct($name);
        $this->position = $position;
    }
  
    public function introduce()
    {
        echo "I am " . $this->name . ", and I work as a " . $this->position . ".";
    }
}

$employee = new Employee("John Doe", "Software Engineer");
$employee->introduce(); // 输出: I am John Doe, and I work as a Software Engineer.

示例3:访问父类的受保护变量

class BaseClass
{
    protected $baseValue = "Base Value";

    public function getBaseValue()
    {
        return $this->baseValue;
    }
}

class DerivedClass extends BaseClass
{
    public function showAndModifyValue()
    {
        // 访问父类的受保护变量并显示
        echo "Original base value: " . parent::$baseValue . "\n";

        // 假设由于某种原因,我们需要使用父类的原始值做一些处理
        $newValue = parent::$baseValue . ", modified in DerivedClass";
      
        // 注意:这里不会改变父类的原始属性值,因为它是受保护的,只能在父类或子类内部访问和修改
        echo "Modified value (but not changing the parent's): " . $newValue . "\n";
    }
}

$derived = new DerivedClass();
$derived->showAndModifyValue();

需要注意的是,parent:: 不可以直接用于访问父类的非静态属性(除非是在父类方法中),因为在子类中直接访问父类的非静态属性通常会导致警告或错误。上述示例中的属性访问主要是通过父类提供的公共或受保护的访问器方法间接完成的。如果确实要在子类中修改父类的受保护属性,必须在子类中定义自己的方法来操作这些属性。


评论