如何从子类访问父变量 [英] how to access parent variable from child class
本文介绍了如何从子类访问父变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个类一个父和另一个扩展,我需要使用main vars在扩展类。
例如
i have two classes one parent and the other extends , I need to use main vars in extended class. for example
class parentClass
{
$this->value = null
function __construct()
{
echo "im parent" ;
}
}
class childClass extends parentClass
{
function sayIt()
{
var_dump($this->value);
}
}
$p = new parentClass ;
$p->value = 500 ;
$c = new childClass ;
$c->sayIt(); // this output null ! i want it to output 500 , how i can do that
感谢
推荐答案
坏坏坏代码严格用于教育目的,我建议你拿一本关于面向对象编程的基本原理的书<
Bad Bad Bad The code is strictly for educational purpose i would advice you to get a book on basic Principles of Object Oriented programming
将您的变量设为静态可以通过子类访问
Making your variable static would make it accessible via the child class
class parentClass {
public static $value = null;
function __construct() {
echo "patent called";
}
}
class childClass extends parentClass {
function sayIt() {
var_dump(self::$value);
}
}
$p = new parentClass();
parentClass::$value = 500;
$c = new childClass();
$c->sayIt();
这篇关于如何从子类访问父变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文