2014-09-23 83 views
0

我想知道這樣的組合是否可能。從類A調用類B並繼承類A的屬性?

classA.php

class A 
{ 
    public $one = "one"; 

    function start() { 

     $this->one = "seven"; 

     include "classB.php"; 
     $two = new B; 
     print_r(get_defined_vars()); 
    } 
} 

classB.php

class B extends A 
{ 
    public $two = "two"; 

    function __construct() { 
     echo($this->one); 
    } 
} 

最後的index.php

include "classA.php"; 
$A = new A; 
$A->start(); 

當我運行的index.php,我得到如下:

Array 
(
    [one] => seven 
    [B] => B Object 
     (
      [two] => two 
      [one] => one 
     ) 
    ) 

有沒有辦法讓B類使用更新的變量?或者我必須將代碼分成兩個文件並單獨使用?這樣它至少工作...但我不喜歡我的代碼在課堂以外,我儘量減少使用全球範圍...

+0

BTW:我知道__construct()的,我寫的代碼不__construct使__construct()根本不會被調用。 – 2014-09-23 22:51:54

+1

你真的應該多讀一點關於繼承的實際工作....如果B類擴展了A類,那麼你應該實例化B類......但是不能通過包含類B中的類B嵌入代碼....那根本不是遺傳 – 2014-09-23 22:53:12

+0

你想達到什麼目的? – sectus 2014-09-23 22:53:16

回答

1

您不必將b類包含到類a中。

只需使用B類擴展A,即可。

在您的輸出中,您創建了一個擴展類A的新對象B,但此B對象是一個與父類無關的新實例。

試試這個:

class A { 
    public $propA = 'Property of A class'; 
} 

class B extends A { 
    public $propB = 'Property of B class'; 
} 

$obj = new B(); 

echo $obj->propA; // returns "Property of A class" 
echo $obj->propB; // returns "Property of B class" 
0

您可以使用靜電。這是一個可怕的做法,但:

class A 
{ 
    public static $one = "one"; 

    function start() 
    { 

     $one = "seven"; 

     $two = new B; 
     print_r(get_defined_vars()); 
    } 
} 

class B extends A 
{ 
    public $two = "two"; 

    function __construct() { 
     echo($this::$one); 
    } 
} 
0

IMO,php.net文檔是有點稀缺。這就是爲什麼我們有Stackoverflow,對此我很感激。感謝提示,我現在意識到了。每天學習新東西。

重點。在index.php中的代碼應該是這樣的:

include "classA.php"; 
include "classB.php"; 

$B = new B; 
print_r(get_defined_vars()); 

$B->start(); 
print_r(get_defined_vars()); 

現在,輸出正是我需要的:

[B] => B Object ([two] => two [one] => one) // before the change 
[B] => B Object ([two] => two [one] => seven) // after the change 
相關問題