2011-07-28 36 views
0

我一直在想下面一段时间: 我正在使用一种构造方式将一些(在本例中为'tool'-)类加载到'parent'或'controller'类的属性中。更具体的:引用'假人父母的属性......?

class a 
    { 
     public $b; 
     public $c; 

     public function __construct() 
     { 
      $this->b = new b(); 
      $this->c = new c(); 
     } 
    } 
    class b 
    { 
     // Properties and methods of b. 
    } 
    class c 
    { 
     // Properties and methods of c. 
    } 
    $a = new a(); 

a和b(和c)不是(分别)“父子”中的一个为之间的关系存在只能一个的实例。到目前为止好,但是:此刻我访问类的成员,类B或C通过得到的一个局部引用呼吁通过“全球” ......所以说:

class a 
    { 
     public $b; 
     public $c; 
     public $a_property = 'something something'; 

     public function __construct() 
     { 
      $this->b = new b(); 
      $this->c = new c(); 
     } 
    } 
    class b 
    { 
     public function test() 
     { 
      global $a; 
      echo $a->a_property; 
     } 
    } 
    class c 
    { 
     // Properties and methods of c. 
    } 
    $a = new a(); 
    $a->b->test(); 

这是一个:丑(我认为),b:(我找不到它的任何文件/参考了,但)我认为,作为PHP 5的下面应该是可能的(?):

class a 
    { 
     public $b; 
     public $c; 
     public $a_property = 'something something'; 

     public function __construct() 
     { 
      $this->b = new b(); 
      $this->c = new c(); 
     } 
    } 
    class b 
    { 
     public function test() 
     { 
      echo $this->a_property; 
     } 
    } 
    class c 
    { 
     // Properties and methods of c. 
    } 
    $a = new a(); 
    $a->b->test(); 

这并未没有工作...虽然服务器运行PHP 5.3.6 ...

奥卡姆的剃刀:我可能错误的功能...! ;-)

回答

0

由于b没有延伸即使aa实例化,它应该能够通过echo a::$a_property;的范围来访问属性,因为现在ba类。

+0

AlienWebguy嗨, 感谢您的回复!但是:我从来没有见过范围解析运算符和对象访问器组合使用...并且它不起作用...(以及变量'$'.. ??)另外:是,“a :: $ a_property“将工作,如果”$ a_property“被宣布为'静态'...这,我宁愿不要做... – IndigoDragon

0

我认为如果你想通过使用“$ this-> a_property”访问“a_property”,B应该扩展a。

class b extends a 

否则,你只要把成分和成分不柏美给进入两班的成员。

什么是错误信息?

+0

嗨Triomen, 感谢您的回复! 是的,这当然会起作用,但正如我所说的,'a'不应该是'b'和/或'c'的'父'... 错误是(好问题!--)): “未定义的属性:b :: $ val” 告诉我:'b'不知道'a'...正确!? – IndigoDragon

+0

两件事。或者,A应该是B的父亲,或者您可以使$ a_property成为静态可访问的。 “$ this”引用类型为“B”的类而不是“A” 如果A只能实例化一次,是不是可以用“singleton”patern实现的父类? – Triomen

0

我认为你应该在PHP了解inheritance :)

编辑:

示例代码:

class a{ 
     public $a_property = 'something something'; 

} 
class b extends a{ 
     public function test() 
     { 
      echo $this->a_property; 
     }   
} 

    $b = new b(); 
    $b->test(); 
+0

嗨Mateusz, 感谢您的回复!是的,我已经意识到这一点,因此(在发布的例子中)使用了“声明全局”方法。我的问题是关于我是否认为'应该是可能的(截至版本5?)' - '因为我在某处读过它。' - 是真的还是不是...... ;-) – IndigoDragon