PHP:从子类访问受保护的变量


PHP: Accessing protected var from child class

我正在学习PHP,我被困在下面的代码:

<?php
class dogtag {
    protected $Words;
}
class dog {
    protected $Name;
    protected $DogTag;
    protected function bark() {
        print "Woof!'n";
    }
}
class poodle extends dog {
    public function bark() {
        print "Yip!'n";
    }
}
$poppy = new poodle;
$poppy->Name = "Poppy";
$poppy->DogTag = new dogtag;
$poppy->DogTag->Words = "My name is
Poppy. If you find me, please call 555-1234";
var_dump($poppy);
?>

这是我得到的:

PHP Fatal error:  Uncaught Error: Cannot access protected property poodle::$Name

这看起来很奇怪,因为我应该从子类访问受保护的变量和函数。

谁能解释一下我错在哪里?

许多谢谢。

确实可以从子类访问受保护的变量。但是,你不能从子类内部访问变量。

如果将变量设置为public,则可以从类外部访问它们。

文档:http://php.net/manual/en/language.oop5.visibility.php

的例子:

Class Dog {
   private $privateProperty = "private"; //I can only be access from inside the Dog class
   protected $protectedProperty = "protected"; //I can be accessed from inside the dog class and all child classes
   public $publicProperty = "public"; //I can be accessed from everywhere.
}

Class Poodle extends Dog {
   public function getProtectedProperty(){
       return $this->protectedProperty; //This is ok because it's inside the Poodle (child class);
   }
}
$poodle = new Poodle;
echo $poodle->publicProperty; //This is ok because it's public
echo $poodle->getProtectedProperty(); //This is ok because it calls a public method.

你不能访问属性" Words ",你需要把它设为public

您可以添加magic方法到您的类-这将允许您从类外部访问和操作私有属性。

class foo{
    private $bah;
    public function __construct(){
        $this->bah='hello world';
    }
    public function __get( $name ){
        return $this->$name;
    }
    public function __set( $name,$value ){
        $this->$name=$value;
    }
    public function __isset( $name ){
        return isset( $this->$name );
    }
    public function __unset( $name ){
        unset( $this->$name );  
    }
}
$foo=new foo;
echo $foo->bah;
$foo->bah='banana';
echo $foo->bah;