2012-05-03 124 views
1

我有一个奇怪的问题,我在父类中设置了值,但无法在扩展父类的子类中访问这些值。访问子类中的父属性值

class Parent 
{ 
    protected $config; 

    public function load($app) 
    { 
     $this->_config(); 
     $this->_load($app); 
    } 

    private function _config() 
    { 
     $this->config = $config; //this holds the config values 
    } 

    private function _load($app) 
    { 
     $app = new $app(); 
     $this->index; 
    } 
} 

class Child extends Parent 
{ 
    public function index() 
    { 
     print_r($this->config); // returns an empty array 
    } 
} 

$test = new Parent(); 
$test->load('app'); 

当我这样做时,我得到一个空的数组打印出来。但如果我这样做,那么我可以访问这些配置值。

private function _load($app) 
{ 
    $app = new $app(); 
    $app->config = $this->config 
    $app->index; 

} 

class Child extends Parent 
{ 
    public $config; 
      .... 
} 

然后我可以从父访问配置数据。

+0

什么是'app'类? –

+0

应用程序类其子类 – Eli

回答

2

在任何初始化之前,您正在访问这些值。首先你必须设定值。

示例:调用方法是在子类的构造器上设置值的父类。

class Child extends Parent 
{ 
    public function __construct() { 
     $this -> setConfig(); //call some parent method to set the config first 
    } 
    public function index() 
    { 
     print_r($this->config); // returns an empty array 
    } 
} 

更新:你似乎也感到困惑OOP

class Parent { ..... } 
class child extends Parent { ..... } 
$p = new Parent(); // will contain all method and properties of parent class only 
$c = new Child(); // will contain all method and properties of child class and parent class 

的概念,但是,你有父母的方法和属性一样的方式,你会在做工作正常的对象。

让我们看看另一个例子:

class Parent { 
    protected $config = "config"; 
} 
class Child extends Parent { 
    public function index() { 
      echo $this -> config; // THis will successfully echo "config" from the parent class 
    } 
}  

但另一个例子

class Parent { 
    protected $config; 
} 
class Child extends Parent { 
    public function index() { 
      echo $this -> config; //It call upon the parent's $config, but so far there has been no attempt to set an values on it, so it will give empty output. 
    } 
} 
+0

hey starx,一周前第一次尝试帮助我之后,我重新编写代码以使其更加简化。现在我回到了同样的问题。我认为扩展父类会继承所有的属性值。 – Eli

+0

@Eli,请参阅更新,我希望它可以帮助:) – Starx

+0

我确定它们只是拼写错误,但范围解析在更新的'$ config'示例中不正确。 –

1

这是因为家长的财产受到保护。将其设置为公开,您可以在子类中访问它。或者,在父类中创建一个返回配置的方法:

public function getConfig() 
{ 
    return $this->config; 
} 
+0

+1用于正确提示OP使用公共访问器。 –

+0

@MikePurcell,$ config被保护,同时破坏创建公共访问器。 – Starx

+0

不知道你的意思是“破坏”,但你是正确的,孩子类应该仍然可以访问受保护的$配置,认为它是私人的某种原因。 –