DogTag = new dogtag; $poppy->DogTag->Words = "My name is-6ren">
gpt4 book ai didi

PHP:从子类访问 protected var

转载 作者:行者123 更新时间:2023-12-05 06:41:51 25 4
gpt4 key购买 nike

我正在学习 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

这对我来说很奇怪,因为我应该从子类访问 protected 变量和函数。

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

非常感谢。

最佳答案

确实可以从子类访问 protected 变量。但是,您没有从子类内部访问您的变量。

如果您将变量设置为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.

关于PHP:从子类访问 protected var,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39325360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com