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");
Why do you have a space after $this
? Remove the space.
Also, add $this
when calling a variable.
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";
}
}
Since $_type
and $_breed
are scoped at the object level, you need to tell PHP what scope you're referencing them in.
Therefore, instead of
echo $_breed;
You need
echo $this->_breed;
On a side note, it's very strange practice to prefix variable names with _ these days, even moreso if they are public variables. This will likely confuse other developers working with your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With