Home >Backend Development >PHP Tutorial >PHP object-oriented public private protected access modifier_PHP tutorial

PHP object-oriented public private protected access modifier_PHP tutorial

WBOY
WBOYOriginal
2016-07-20 11:16:37878browse

This article is a detailed analysis and introduction to the PHP object-oriented public private protected access modifier. Friends who need it can refer to it. ​

There are three access modifiers in PHP, namely:
public (public, default)
protected
private
public (public, default) In PHP5, if a class does not specify an access modifier for a member, the default is public access.
protected (protected) A member declared as protected is only accessible by subclasses of the class.
Private (Private) Members defined as private are visible to all members within the class and have no access restrictions. Access is not allowed outside the class.

Illustration

demo

Copy code The code is as follows:


class Woman{
public $name = "gaojin";
protected $age = "22";
private $height = "170";
function info(){
echo $this->name;
}
private function say(){
echo "This is a private method";
}
}
//$w = new Woman();
//echo $w->info();
//echo $w->name;//Public properties can be accessed
//echo $w->age;// Protected attribute, fatal error reported
//echo $w->height;// Protected attribute, fatal error reported
//Private method, access error
//$w->say(); // Private method, access error
class Girl extends Woman{
// You can redefine the public and protected methods of the parent class, but you cannot define the private
//protected $name = "jingao"; // Can be redefined
function info(){
echo $this->name;
echo $this->age;
echo $this->height;
}
function say(){
//parent::say();//Private methods cannot be inherited. If the parent class’s say method is protected, no error will be reported here
echo "I'm a girl";
}
}
$g = new Girl();
$g->say();//Normal output
//echo $g->height;//The private property cannot be accessed and no result is output
//$g->info();//This is the output gaojin22 $height is a private property and is not inherited
//$g->height ="12";//Here is the height attribute redefined and assigned a value
//$g->info();//So the output here will be gaojin2212

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/372377.htmlTechArticleThis article is a detailed analysis and introduction to the PHP object-oriented public private protected access modifier. Friends who need it For reference, there are three access modifiers in PHP, namely: publ...
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