What is the difference between public, private, and protected?

后端 未结 17 1600
抹茶落季
抹茶落季 2020-11-21 07:54

When and why should I use public, private, and protected functions and variables inside a class? What is the difference between them?<

17条回答
  •  梦毁少年i
    2020-11-21 08:17

    /**
     * Define MyClass
     */
    class MyClass
    {
        public $public = 'Public';
        protected $protected = 'Protected';
        private $private = 'Private';
    
        function printHello()
        {
            echo $this->public;
            echo $this->protected;
            echo $this->private;
        }
    }
    
    $obj = new MyClass();
    echo $obj->public; // Works
    echo $obj->protected; // Fatal Error
    echo $obj->private; // Fatal Error
    $obj->printHello(); // Shows Public, Protected and Private
    
    
    /**
     * Define MyClass2
     */
    class MyClass2 extends MyClass
    {
        // We can redeclare the public and protected method, but not private
        protected $protected = 'Protected2';
    
        function printHello()
        {
            echo $this->public;
            echo $this->protected;
            echo $this->private;
        }
    }
    
    $obj2 = new MyClass2();
    echo $obj2->public; // Works
    echo $obj2->private; // Undefined
    echo $obj2->protected; // Fatal Error
    $obj2->printHello(); // Shows Public, Protected2, Undefined
    

    Extracted From :

    http://php.net/manual/en/language.oop5.visibility.php

提交回复
热议问题