2012-05-07 33 views
0

當我運行下面的代碼時我得到了錯誤echo $attribute; 錯誤代碼:「可捕捉的致命錯誤:類SomeShape的對象無法轉換爲字符串」: 這個代碼? 謝謝。我想要初始化屬性而不創建對象

<?php 

    class Shape 
    { 
     static public $width; 
     static public $height; 
    } 

class SomeShape extends Shape 
    { 
     public function __construct() 
     { 
     $test=self::$width * self::$height; 
     echo $test; 
     return $test; 
     } 
    } 

    class SomeShape1 extends Shape 
    { 
     public function __construct() 
     { 
     return self::$height * self::$width * .5; 
     } 
    } 

    Shape::$width=60; 
    Shape::$height=5; 
    echo Shape::$height; 
    $attribute = new SomeShape; 
    echo $attribute; 
    $attribute1 = new SomeShape1; 
    echo $attribute1; 
?> 
+0

這可能幫助你http://stackoverflow.com/questions/829823/can-you-create-class-properties-dynamically-in-php –

+0

哪條線路會導致錯誤? – Brady

回答

1

你所試圖做的是迴應一個對象,它就像你正在呼應的數組(最糟糕的不是附和,因爲數組迴應一個對象throuws錯誤),而你應該做的是訪問它的屬性或方法等。但是,如果你想c什麼在你的對象,你必須使用var_dump而不是回聲。

總之,回聲$屬性是錯誤的。用var_dump($屬性)

+0

好吧,我找到解決方案,我不想添加更多的屬性類的形狀,但這解決了我的問題,因爲我wish.may有更多類似的解決方案,我很樂意看到。但這是我的想法 我在類中定義了「public $ attribute;」 SomeShape我的 「公共職能__construct()」 寫的類中 「$這個 - >屬性=自:: $寬*自:: $高度;」 在主範圍中,我寫了「echo $ object-> attribute」。
「;」 –

1

不要在構造函數中做return

如果你想呼應的值,改掉添加__toString()功能(manual

1

你不能沒有實現__toString方法呼應的對象。

另外,您可以var_dump對象:

var_dump($attribute); 

但我想你實際上是試圖做的是什麼更多像這樣的:

class Shape { 
    public $width; 
    public $height; 

    public function __construct($width, $height) { 
     $this->width = $width; 
     $this->height = $height; 
    } 
} 

class SomeShape extends Shape { 
    public function getArea() { 
     return $this->width * $this->height; 
    } 
} 

class SomeShape1 extends Shape { 
    public function getHalfArea() { 
     return $this->width * $this->height * .5; 
    } 
} 

$shape = new SomeShape(10, 20); 
echo $shape->getArea(); 

$shape = new SomeShape1(10, 20); 
echo $shape->getHalfArea(); 
0

,我找到了解決辦法是: 我不我不想給課堂形狀增加更多的屬性,但這可以解決我的問題,因爲我希望能有更多類似的解決方案,我很樂意看到。但這是我的想法,我在課堂上定義了「public $ attribute」屬性;在SomeShape類中,我在「public function __construct()」上寫了「$ this-> attribute = self :: $ width * self :: $ height;」在主範圍中,我寫了「echo $ object-> attribute」。
「;」

<?php 

    class Shape 
    { 
     static public $width; 
     static public $height; 
     public $attribute; 
    } 

class SomeShape extends Shape 
    { 

     public function __construct() 
     { 
     $this->attribute=self::$width * self::$height; 
     } 
    } 

    class SomeShape1 extends Shape 
    { 
     public function __construct() 
     { 
     $this->attribute=self::$width * self::$height * .5; 
     } 
    } 

    Shape::$width=60; 
    Shape::$height=5; 


    $object = new SomeShape; 
    echo $object->attribute."<br />"; 

    $object1 = new SomeShape1; 
    echo $object1->attribute; 
?>