我想在不创建对象的情况下初始化属性


I want to initialize attribute without creating object

当我运行下面的代码时,我在第 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;
?>

您要做的是回显一个对象,就像您正在回显一个数组一样(比回显数组更糟糕,因为回显对象错误),而您应该做的是访问它的属性或方法等。但是,如果您想c对象中的内容,则必须使用var_dump而不是echo。

简而言之,回声$attribute是错误的。使用 var_dump($attribute)

不要在构造函数中执行return

如果要回显值,请尝试添加__toString()函数(手动)

如果不实现 __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();

我找到的解决方案是:我不想在类形状中添加更多属性,但这可以随心所欲地解决我的问题。但这是我的想法,我用阶级形式定义"公共$attribute";在类 SomeShape 中,我写了"公共函数 __construct()" "$this->attribute=self::$width * self::$height;"在主要范围内,我写了"echo $object->属性"。
";"

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