简体   繁体   中英

Calling instance method from a static method of the same class - safe or not?

I'm a bit puzzled here as to how come the following PHP code works:

class A
{
    private function test()
    {
        print('test' . PHP_EOL);
    }
    
    static public function makeInstanceAndCall()
    {
        $test = new A();
        $test->test();
    }
}

A::makeInstanceAndCall();

$test = new A();
$test->test();

The last line call of the test() method obviously fails but how come calling the same method from the static context of the makeInstanceAndCall() method doesn't seem to.

Is it safe to rely on this sort of behaviour in a production environment?

And what PHP feature am I possibly missing that makes this work. I've just spent some time browsing through PHP documentation but couldn't really find a definitive answer.

Thanks.

What you're missing here, is that in PHP private keyword doesn't mean that this property of an object can be only used by this object itself.

Private menas, that this property can only be used INSIDE this class. It doesn't require to be in this object context.

Your'e $test->test(); is inside class A , so it can use it's private properties ;)

Look at this example:

class A
{
    private string $name;
    
    public function __construct($name) {
        $this->name = $name ;
    }
    
    private function sayName()
    {
        print('My name is ' . $this->name);
    }
    
    public function sayAnotherObjectName( self $anotherObject ) {
     $anotherObject->sayName();   
    }
    
}

$John = new A('John');
$Anie = new A('Anie');
$John->sayAnotherObjectName($Anie);

From function sayAnotherObjectName() you can call your private sayName() function, even in the context of another object! So, the output of the above code is: My name is Anie

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM