The Street Way

'Private' Access Control Modifiers

Private

Private properties are accessible only inside the methods of the class that defined them. If a new class inherits from it, the properties will not be available in the methods of that new class; they remain accessible only in the functions from the original class. For example:

Ex. -> class A {
                private $Name;
               private $ATag;

    public function setName($NewName) {
                    // Statement Description here .
            }
    }

Both $Name and $ATag are private, which means no one can access them unless they are doing so in a method that is part of the class, such as setName( ). This remains public because we want this to be accessible by anyone.

Now if our nosey programmer comes along and tries to set $Name directly, using code like $p->Name, he will not get what he was expecting: PHP will give him the error message: "Cannot access private property A::$Name". However, if that private property were inherited from another class, PHP will try to accommodate his request by having a private property and a public property. Yes, this is confusing; however, the following code should clear things up:

Ex. class A {
     
          private $Name;
        }

    class B extends A { }

    $p = new B;
    $p->Name = "XYZ";
    print_r($p);

Running that script will output the following:

    b Object
    (
    [Name:private] =>
    [Name] => XYZ
    )

Notice that there are two Name properties one that is private and cannot be touched, and another that PHP creates for local use as requested. Clearly this is confusing, and you should try to avoid this situation, if possible.

Keep in mind that private methods and properties can only be accessed by the exact class that owns them,child classes cannot access private parent methods and properties. If you want to do this, you need the protected keyword instead.

0 comments:

Post a Comment