Home  >  Article  >  Backend Development  >  Access control in PHP5! public,private,protected_PHP tutorial

Access control in PHP5! public,private,protected_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:37:39911browse

The variable definition of the 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 and can only be accessed in this class or subclass or parent class;

class BaseClass {
public $public = public;
private $private = private;
protected $protected = protected;

function __construct(){

}

function print_var(){
print $this->public;echo
;
print $this->private; echo
;
print $this->protected; echo
;
}

}

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 Protected, so it can be used in this class or subclass, and the value can be paid repeatedly in subclasses
echo
;
echo $this->private;//error because it is private
}
}

can only be used in the baseclass that defines it.

$obj1 = new BaseClass();
$obj1->print_var();
//echo $obj1->protected;//error because it is protected, only within this class Or you can call
//echo $obj1->private;//error in the subclass or parent class. Private as above, only call
echo $obj1->public;
echo "


";
$obj2 = new Subclass();
echo
;
echo $obj2->public;echo
;
echo $obj2->protected;
//echo $obj2->private;//error
//echo $obj2->protected;
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/486555.htmlTechArticleThe variable definition of the class in php5 oop follows an access control, which is: public means global, internal and external subclasses of the class All can be accessed; private means private and can only be used within this class...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn