Monday, 6 April 2015

Differences between Public,Private and Protect


Public: When you declare a method (function) or a property (variable) as public, those methods and properties can be accessed by: The same class that declared it. The classes that inherit the above declared class. Any foreign elements outside this class can also access those things. Example: name; // The public variable will be available to the inherited class } } // Inherited class Daddy wants to know Grandpas Name $daddy = new Daddy; echo $daddy->displayGrandPaName(); // Prints 'Mark Henry' // Public variables can also be accessed outside of the class! $outsiderWantstoKnowGrandpasName = new GrandPa; echo $outsiderWantstoKnowGrandpasName->name; // Prints 'Mark Henry' Protected: When you declare a method (function) or a property (variable) as protected, those methods and properties can be accessed by The same class that declared it. The classes that inherit the above declared class. Outsider members cannot access those variables. "Outsiders" in the sense that they are not object instances of the declared class itself. Example: name; } } $daddy = new Daddy; echo $daddy->displayGrandPaName(); // Prints 'Mark Henry' $outsiderWantstoKnowGrandpasName = new GrandPa; echo $outsiderWantstoKnowGrandpasName->name; // Results in a Fatal Error The exact error will be this: PHP Fatal error: Cannot access protected property GrandPa::$name Private: When you declare a method (function) or a property (variable) as private, those methods and properties can be accessed by: The same class that declared it. Outsider members cannot access those variables. Outsiders in the sense that they are not object instances of the declared class itself and even the classes that inherit the declared class. Example: name; } } $daddy = new Daddy; echo $daddy->displayGrandPaName(); // Results in a Notice $outsiderWantstoKnowGrandpasName = new GrandPa; echo $outsiderWantstoKnowGrandpasName->name; // Results in a Fatal Error The exact error messages will be: Notice: Undefined property: Daddy::$name Fatal error: Cannot access private property GrandPa::$name

PHP Built-in Functions