Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize variable in constructor in PHP

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");
like image 446
Vikas S. Avatar asked Dec 10 '22 16:12

Vikas S.


2 Answers

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";
    }
}
like image 70
Jerodev Avatar answered Dec 30 '22 01:12

Jerodev


You are initializing them fine, but retrieving them wrong...

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.

like image 44
Matt Prelude Avatar answered Dec 30 '22 01:12

Matt Prelude