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;
?>
4

4 に答える 4

1

returnコンストラクターでを実行しないでください。

値をエコーし​​たい場合は、__toString()関数を追加しようとします(手動

于 2012-05-07T09:38:14.367 に答える
1

あなたがやろうとしているのは、オブジェクトをエコーすることです。これは、配列をエコーするのと同じです(オブジェクトをエコーするとエラーが発生するため、配列をエコーするよりも最悪です)、その属性やメソッドなどにアクセスする必要があります。 cオブジェクトの内容については、echoの代わりにvar_dumpを使用する必要があります。

つまり、echo$attributeが間違っています。var_dump($ attribute)を使用します

于 2012-05-07T09:40:49.440 に答える
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();
于 2012-05-07T10:09:47.477 に答える
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;
?>
于 2012-05-08T04:19:19.993 に答える