WHEN do I use public, protected or private keyword? Here's the default behavior.
<?php
class Example
{
/* use PUBLIC on variables and functions when:
* 1. outside-code SHOULD access this property or function.
* 2. extending classes SHOULD inherit this property or function.
*/
public $var1;
public function someFunction_1() { }
/* use PROTECTED on variables and functions when:
* 1. outside-code SHOULD NOT access this property or function.
* 2. extending classes SHOULD inherit this property or function.
*/
protected $var2;
protected function someFunction_2() { }
/* use PRIVATE on variables and functions when:
* 1. outside-code SHOULD NOT access this property or function.
* 2. extending classes SHOULD NOT inherit this property or function.
*/
private $var3;
private function someFunction_3() { }
}
# these are the only valid calls outside-code can make on Example objects:
$obj1 = new Example(); // instantiate
$var1 = $obj1->var1; // get public data
$obj1->var1 = 35; // set public data
$obj1->someFunction_1(); // call public function
?>
Now try extending the class...
<?php
class Example_2 extends Example
{
// this class inherits the following properties and functions.
public $var1;
public function someFunction_1() { }
protected $var2;
protected function someFunction_2() { }
}
# these are the only valid calls outside-code can make on Example_2 objects:
$obj2 = new Example_2(); // instantiate
$var2 = $obj2->var1; // get public data
$obj2->var1 = 45; // set public data
$obj2->someFunction_1(); // call public function
?>
----
Server IP: 69.147.83.197
Probable Submitter: 67.150.124.172
----
Manual Page -- http://www.php.net/manual/en/language.oop5.visibility.php
Edit -- https://master.php.net/note/edit/86266
Del: integrated -- https://master.php.net/note/delete/86266/integrated
Del: useless -- https://master.php.net/note/delete/86266/useless
Del: bad code -- https://master.php.net/note/delete/86266/bad+code
Del: spam -- https://master.php.net/note/delete/86266/spam
Del: non-english -- https://master.php.net/note/delete/86266/non-english
Del: in docs -- https://master.php.net/note/delete/86266/in+docs
Del: other reasons-- https://master.php.net/note/delete/86266
Reject -- https://master.php.net/note/reject/86266
Search -- https://master.php.net/manage/user-notes.php
lmpx.com only provides a reader for public news (NNTP) servers. It is not
affiliated with the servers or forums shown here and is not responsible for
the content of articles, which is written by their respective authors.