John Davidson

class - php static property

0 comments
Message:


I have two code snippets (regarding the static keyword) which I expect them to have same output, but actually the outputs are different.



The question is why?



Snippet 1



class base
{
public static $var = 1;
}

class sub extends base
{
public static $var = 2;
}

echo base::$var; // Outputs 1



1




Snippet 2



class base2
{
public static $var2 = 1;
}

class sub2 extends base2
{
}

sub2::$var2 = 2;
echo base2::$var2; // Outputs 2



2




My Answer:
The reason why the outputs are different in the two code snippets is because in the first snippet, the static property $var is being overridden in the subclass "sub" by redeclaring it with a new value. So when you echo base::$var, it still refers to the static property $var in the base class which has a value of 1.

In the second snippet, you are directly assigning a new value to the static property $var2 in the subclass "sub2" without redeclaring it. So when you echo base2::$var2, it refers to the static property $var2 in the base class which has been updated to a value of 2.

In summary, in the first snippet, the static property is being overridden in the subclass, while in the second snippet, the static property in the base class is being directly modified.

Rate this post

4 of 5 based on 2522 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us