Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 692
Chris Roy Avatar asked Sep 18 '25 23:09

Chris Roy


2 Answers

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

like image 179
Rajib Ghosh Avatar answered Sep 20 '25 13:09

Rajib Ghosh


That happens because you're "presenting it" by echo'ing it. You can't reference it like this for example:

class test {
    private $a = 'b';

    function __construct() {
        echo 'instantiated';
    }
}

$test = new test();
echo $test->a; // This line won't work, since it's a private var.

It would give you an error message that looks like this:

Fatal error: Cannot access private property test::$a

Example (https://eval.in/226435)


As I said before, you're accessing it from within the class itself, so you CAN view it. (That's the $instance you have there.) If you modify your code to use it like this:

 class test {
   protected $a = "b";

   public static function oo(){
     $instance = new static();
     return $instance;
   }
 }

echo test::oo()->a;

Example of the above (https://eval.in/226439)

You'll get that "private acess blah blah" error.

You're understanding the statement wrong. "private and protected cannot be referenced from outside the class" means that as the examples above show, you CAN NOT access the variables outside the class, but with your example, you're accessing it from INSIDE the class, which means they'll do as you require (echo'ing out as you did)

like image 25
Darren Avatar answered Sep 20 '25 15:09

Darren