Home >Backend Development >PHP Tutorial >PHP object-oriented public private protected three modifier code examples

PHP object-oriented public private protected three modifier code examples

伊谢尔伦
伊谢尔伦Original
2017-07-03 09:57:281828browse

This article is a detailed analysis and introduction to php object-orientedpublic private protected access modifiers. Friends in need can refer to it

There are three access modifiers in PHP symbols, respectively:
public (public, default)
protected (protected)
private (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) Members declared as protected are only allowed to be accessed by subclasses of this 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

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 "这是私有的方法";
    }
}
//$w = new Woman();
//echo $w->info();
//echo $w->name;//公共
属性
可以访问
//echo $w->age;// 受保护属性,报致命错误
//echo $w->height;// 受保护属性,报致命错误
//私有方法,访问出错
//$w->say(); // 私有方法,访问出错
class Girl extends Woman{
    // 可以重新定义父类的public和protected方法,但不能定义private的
  //protected $name = "jingao"; // 可以从新定义
    function info(){
        echo $this->name;
        echo $this->age;
        echo $this->height;
    }
    function say(){
        //parent::say();//私有方法 不能被
继承
  如果父类的的say方法是protected 这里就不会报错
        echo "我是女孩";
    }
}
$g = new Girl();
$g->say();//正常输出
//echo $g->height;//私有属性访问不到 没输出结果
//$g->info();//这是输出 gaojin22 $height是私有的属性没有被继承
//$g->height ="12";//这里是重新定义 height属性 也赋值了 
//$g->info();//所以这里会输出来gaojin2212


The above is the detailed content of PHP object-oriented public private protected three modifier code examples. For more information, please follow other related articles on the PHP Chinese website!

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