The variable definition of a class in php5 oop follows an access control, which is:
public means global, and can be accessed by subclasses inside and outside the class;
private means private, and can only be used within this class;
protected means protected, only this class or Can be accessed in subclasses or parent classes;
<?php
class BaseClass {
public $public = 'public';
private $private = 'private';
protected $protected = 'protected';
function __construct(){
}
function print_var(){
print $this->public;echo '<br />';
print $this->private; echo '<br />';
print $this->protected; echo '<br />';
}
}
class Subclass extends BaseClass {
// public $public = 'public2';
protected $protected ='protected2';
function __construct(){
echo $this->protected;//Can be accessed, because the class is defined as protected, so it can be in this class or subclass, and the value can be repeated in subclasses
echo '<br />';
echo $this->private;//error because it is private and can only be used in the class baseclass in which it is defined.
}
}
$obj1 = new BaseClass();
$obj1->print_var();
//echo $obj1->protected;//error Because it is protected, it can only be called within this class or in subclasses and parent classes.
//echo $obj1->private;//error private as above, can only be called within this class
echo $obj1->public;
echo "<hr />";
$obj2 = new Subclass();
echo '<br />';
echo $obj2->public;echo '<br />';
echo $obj2->protected;
//echo $obj2->private;//error
//echo $obj2->protected;
?>