Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I initialize variables in a class?

Why do I have to initialize variables in a class?

$test = new myclass();
class myclass {
    private $var; // WHY THIS LINE?

    public function sayHello() {
        $this->var = 'hello';
        echo $this->var;
    }
}
$test -> sayHello();

When I remove the line with private $var; this example works too.

Why do I have to initialize variables in classes?

like image 644
user2753885 Avatar asked Feb 19 '26 15:02

user2753885


1 Answers

Initializing variables has some benefits:

  • You declare that you intentionally want to use the variable name. This can help highlight typos which become undeclared varible name
  • You can set the scope of the variable. Do you want it to be public, protected or private? You might want it to be static
  • PHP has some info about what you're doing. It may help it to optimize for faster execution.

It's good practice to declare your variables, but it isn't a requirement.

like image 137
michaelward82 Avatar answered Feb 22 '26 04:02

michaelward82



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!