PHP/Class/protected

Материал из Web эксперт
Перейти к: навигация, поиск

Class members" visibility

 
public: can be accessed by any other code
private: can be accessed only from within the same class. 
protected: may be accessed from within the class and from within any class that extends that class.



Class using access control

 
class Person {
    public $name;     
    protected $age;   
    private $salary;  
    public function __construct() {
    }
    protected function set_age() {
    }
    private function set_salary() {
    }
}



Private and protected variables

 
<?php
class Staff
{
    private $name;
    private $title;
    protected $wage;
    protected function clockIn() {
        echo "Member $this->name clocked in at ".date("h:i:s");
    }
    protected function clockOut() {
        echo "Member $this->name clocked out at ".date("h:i:s");
    }
}
?>



Properties and methods marked as protected are accessible only through the object that owns them

 
<?
    class Dog {
            public $Name;
            private function getName( ) {
                    return $this->Name;
            }
    }
    class Poodle extends Dog {
            public function bark( ) {
                    print ""Woof", says " . $this->getName( );
            }
    }
    $poppy = new Poodle;
    $poppy->Name = "Poppy";
    $poppy->bark( );
?>



protected member variable

<?php
   class Staff
   {
      protected $name;
      protected $title;
      function __construct()
      {
         echo "<p>Staff constructor called!</p>";
      }
   }
   class Manager extends Staff
   {
      function __construct()
      {
         parent::__construct();
         echo "<p>Manager constructor called!</p>";
      }
   }
   $employee = new Manager();
?>