Lately I’ve been wondering if there’s a difference between initializing the variables that have a default value on the Constructor VS on the class definition.
Which one is better, taking into consideration the optimization:
class TestClass
{
private $test_var = 'Default Value';
function __construct()
{
}
}
class TestClass2
{
private $test_var;
function __construct()
{
$this->test_var = 'Default Value';
}
}
The advantage of initializing properties outside of the constructor is that someone reading your code will immediatly know its a default value.
Inconvenient is you cannot use every kind of data this way — will not work with object instanciations, for instance, or with heredoc syntax, from what I recall.
I don’t think there is much of a difference when it comes to performance — anyway, there are probably lots of things that matter a lot more, in your application 😉
Still, purely for fun, using the Vulcan Logic Disassembler :
With the first example of code (
temp-2.php) :You get these opcodes :
While, with the second example of code (
temp-3.php) :You get those opcodes :
So, I’m guessing there is a bit of a difference… But not that important ^^
Up to you to interpret the opcodes — but the funny thing is there is no trace of ‘
Default Value‘ in the first dump… interesting, actually ^^Seems VLD cannot (or just doesn’t) dump everything 🙁