-1

我对 OOP 真的很陌生,我在第一次实现 __constructor 方法时遇到了一些错误。这两个错误是:

Notice: Undefined variable: _test in...

Fatal error: Cannot access empty property in ...

这是我的代码:

<?php


class Info
{
    private static $_test;

    public function __construct()
    {
        $this->setIt(); //call setIt so $_test can be set to true or false for use by other functions in the class.
    }
    public function setIt()
    {
        if ("test" == "something") //simplified logic for demo purposes
            $this->$_test = TRUE;
        else
            $this->$_test = FALSE;
    }

    public function getIt()
    {
        if ($this->$_test) { //if test is true or false do stuff/other stuff
            //do stuff
        } else {
            //do other stuff
        }
    }
}
$myObj = new Info(); //initialise the object

?>
<?php echo $myObj->getIt(); ?> //surrounded by html in my original code. Here I am getting some 'stuff' or 'other stuff' depending on what setIt() returned to $_test.

对不起,如果这有点令人费解。

4

3 回答 3

1

代替

$this->$_test = TRUE;

$this->_test = TRUE;

你代码中的每一个地方。

使用$thisthen$时不与属性名称一起使用

这个线程可能很有用。

于 2013-05-28T11:17:19.477 回答
1

您以 $ 开头访问您的财产。在对象范围内访问对象属性时,不需要使用$. 但是,您已声明$_test为静态,因此您可以使用设置/获取它们self::$_test

class Info
{
    private static $_test;

    public function __construct()
    {
        $this->setIt(); 
    }

    public function setIt()
    {
        if ("test" == "something"){
            self::$test = TRUE;
        } else {
            self::$test = FALSE;
    }

    public function getIt()
    {
        if (self::$_test) { 
            //do stuff
        } else {
            //do other stuff
        }
    }
}
$myObj = new Info(); //initialise the object

echo $myObj->getIt();
于 2013-05-28T11:19:51.677 回答
1

你定义$_teststatic,所以你应该访问它:

self::$_test

或者

static::$_test

尽管如此,getter 和 setter 应该是有意义的,并且以它们包装的字段 [ie getTest(), setTest($value)] 命名,即使您只是提供一个示例案例。

如果您是 OOP 新手,那么在理解实例与static属性和方法之间的区别时会遇到一些麻烦。

让我们假设有一个Circle类,它包含中心和半径:

class Circle
{

  public static PI = 3.141592653589793;

  private $x;
  private $y;
  private $radius;

  public function getX(){ return $this -> x;}
  public function setX($x){ $this -> x = $x;}

  public function getY(){ return $this -> y;}  
  public function setY($y){ $this -> y = $y;}

  public function getRadius(){ return $this -> radius;}  
  public function setRadius($radius){ $this -> radius = $radius;}  

  public function __construct($x, $y, $radius)
  {

    $this -> setX($x);
    $this -> setY($y);
    $this -> setRadius($radius);

  }

  public function getArea()
  {

    return $this -> radius * $this -> radius * self::PI;

  }

  public function getLength()
  {

    return 2 * self::PI * $this -> radius;

  }

}

xy并且radius对于您构建的每个圆圈[类的实例]都不同:它们是实例变量

$firstCircle = new Circle(0,0,10);
$secondCircle = new Circle(5,5,2);
...

另一方面,PI它是静态的,因为它属于类本身:对于每个圆,它认为长度/直径比为 3.1415...

您会发现静态属性和方法在 OOP 中有更广泛的用途,但这足以让您初步了解它。

于 2013-05-28T11:19:59.877 回答