0

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.

  • 1
    private methods can be used only by its class members, and a static method can be invoked without creating a class instance, so everything works as expected. – svyat1s Oct 09 '20 at 11:30
  • That's a bad practice. Access modifiers are used to provide access for the class methods and members. Private should be used within a class, if you need any function or might need in future then should give it public access modifier. :) – Al-Amin Oct 09 '20 at 11:37
  • [accessing-a-public-private-function-inside-a-static-function](https://stackoverflow.com/questions/16428457/accessing-a-public-private-function-inside-a-static-function/16428582) might help – jibsteroos Oct 09 '20 at 11:40

1 Answers1

0

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

Przemysław Niemiec
  • 1,704
  • 1
  • 11
  • 14