如何在PHP中初始化构造函数中的变量

时间:2016-05-16 11:27:30

标签: php constructor

我正在编写这个简单的代码,不知道构造函数的问题是什么:

class Animal {
    public $_type;
    public $_breed;

    public function __construct ($t, $b) {
        echo "i have initialized<br/>";

        $this ->_type = $t; 
        $this ->_breed = $b;
        echo "type is " .$_type. "<br/>";

        echo "breed is " .$_breed. "<br/>";
    }

    public function __destruct () {
        echo "i am dying";
    }
}

$dog = new Animal("Dog", "Pug");

5 个答案:

答案 0 :(得分:4)

为什么$this之后有空格?删除空格。
另外,在调用变量时添加$this

class Animal {
    public $_type;
    public $_breed;

    public function __construct ($t, $b) {
        echo "i have initialized<br/>";

        $this->_type = $t; // <-- remove space
        $this->_breed = $b;  // <-- remove space
        echo "type is " .$this->_type. "<br/>"; // <-- add $this

        echo "breed is " .$this->_breed. "<br/>"; // <-- add $this
    }

    public function __destruct () {
        echo "i am dying";
    }
}

答案 1 :(得分:3)

你正在初始化它们,但检错了......

由于$_type$_breed的范围是对象级别,因此您需要告诉PHP您在哪个范围内引用它们。

因此,而不是

echo $_breed;

你需要

echo $this->_breed;

另一方面,如今,使用_作为变量名称的前缀是非常奇怪的做法,如果它们是公共变量,甚至更多。这可能会使使用您的代码的其他开发人员感到困惑。

答案 2 :(得分:1)

$ _ type和$ _breed是类的变量,因此您需要使用this关键字

 echo "type is " .$this->_type. "<br/>";
    echo "breed is " .$this->_breed. "<br/>";

答案 3 :(得分:1)

试试这个(注意回声线):

_author

答案 4 :(得分:1)

虽然这没有违反php的语法,但我建议这两行

echo "type is " .$dog->_type. "<br/>";
echo "breed is " .$dog->_breed. "<br/>";

不得放在__construct()而是在课外使用

像这样,

class Animal {
  public $_type;
  public $_breed;

  public function __construct ($t, $b) {
    $this ->_type  = $t;
    $this ->_breed = $b;
  }
  public function __destruct () {
      echo "i am dying";
  }
}

$dog = new Animal("Dog", "Pug");
echo "i have initialized<br/>";
echo "type is " .$dog->_type. "<br/>";
echo "breed is " .$dog->_breed. "<br/>";