Home > Net >  Why PHP visibility like private property can still be modified and accessed?
Why PHP visibility like private property can still be modified and accessed?

Time:08-11

I am thinking why php added visibility such as private, protected, and public when you can still access it using arrow functions? Please see code below

Code

<?php

class Foo
{
  private $secret = 'foo';
}

$foo = new Foo();

(fn() => $this->secret = 'bar')->call($foo);

echo (fn() => $this->secret)->call($foo);

Output

bar

PHP Code Snippet

CodePudding user response:

As you know private properties are not inherited so you are not really accessing private variable itself, so what really happening here is that when you are trying to access your private property from the class object, PHP can't find it So it's dynamically creating new public one for you.

So use Protected properties instead because they are inherited and that's why you can't access them from other parts of the code.

checkout the docs for more information.

CodePudding user response:

This behavior is working as expected because the closure you are using is bounded to the current object's class scope you pass in the first parameter of call method.

So naturally, all private, protected, public members of the current class will be accessible.

Below, is a demonstration to prove this when we try to access private property of a parent class private variable, yet accessing and modifying our own private member variable works just fine.

Snippet:

<?php


class Bar{
  private static $barSecret = 'bar';
}

class Foo extends Bar{
  private $fooSecret = 'foo';
  
  public function getFooSecret(){
    return $this->fooSecret;
  }
  
  public function printBarSecret(){
    echo parent::$barSecret;
  }
}

$foo = new Foo();

(fn() => $this->fooSecret .= " callback append")->call($foo);

echo $foo->getFooSecret();

(fn() => $this->printBarSecret())->call($foo);

Online Demo

  •  Tags:  
  • php
  • Related