Search code examples
phpclassoopvisibility

How can protected property of a class be visible from a static method in PHP?


I understand OOP. What I understand so far is that private and protected cannot be referenced from outside the class using $this->blah notation. If that is correct, how can the following code work?

<?php

 class test {
   protected $a = "b";

   public static function oo(){
     $instance = new static();
     echo $instance->a;
   }
 }

 test::oo();

Gives me an output of b! Now, how in Lord's name can that happen?


Solution

  • In PHP 5.3, a new feature called late static bindings was added – and this can help us get the polymorphic behavior that may be preferable in this situation. In simplest terms, late static bindings means that a call to a static function that is inherited will “bind” to the calling class at runtime. So, if we use late static binding it would mean that when we make a call to “test::oo();”, then the oo() function in the test class will be called.after that you return $instance->a; static keyword allows the function to bind to the calling class at runtime.so if you use static then whatever access modifier(private,public,protected) you use it's just meaning less...

    please read this link,another