如何在PHP中初始化构造函数中的变量(How to initialize variable in constructor in PHP)
我正在写这个简单的代码,不知道构造函数的问题是:
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");I am writing this simple code and do not know what the issue with constructor is:
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");最满意答案
试试这个(注意回声线):
class Animal { public $_type; public $_breed; public function __construct ($t, $b) { echo "i have initialized<br/>"; $this->_type = $t; $this->_breed = $b; //You have to use '$this' keyword to access //class attibutes: echo "type is " . $this->_type . "<br/>"; echo "breed is " . $this->_breed . "<br/>"; } public function __destruct () { echo "i am dying"; } }Try this (note the echo lines):
class Animal { public $_type; public $_breed; public function __construct ($t, $b) { echo "i have initialized<br/>"; $this->_type = $t; $this->_breed = $b; //You have to use '$this' keyword to access //class attibutes: echo "type is " . $this->_type . "<br/>"; echo "breed is " . $this->_breed . "<br/>"; } public function __destruct () { echo "i am dying"; } }更多推荐
发布评论