php的访问控制符有哪些

来自:互联网
时间:2021-07-15
阅读:

访问控制修饰符列表

访问修饰符 含义
Public 将属性或方法设置为可从任何地方访问
Private 将属性或方法设置为只能由其自己的类或对象访问
Protected 将属性或方法设置为可由其类或其后代访问

public

公共属性和方法可以从任何地方访问。

<?PHP
class Book {
        public $Name;
        public function say() {
                print "PHP!\n";
        }
}
class PythonBook extends Book {
        public function say() {
                print "Python!\n";
        }
}
$aBook = new PythonBook;
$aBook->Name = "Python";
print $aBook->Name;
?>

默认情况下,所有类方法都是public的。

上面的代码生成以下结果。

php的访问控制符有哪些

private

私有属性只能在自己的类中访问。

<?PHP
class Book {
        private $Name;
        private $NameTag;
        public function setName($NewName) {
                // etc
        }
}
?>

子类无法访问私有父方法和属性。如果你想这样做,你需要protected关键字。

Protected

受保护的属性和方法可在其自己的类和子类中访问。考虑下面的代码:

<?PHP
class Book {
        public $Name;
        protected function getName() {
                return $this->Name;
        }
}
class Poodle extends Book {
        public function say() {
                print ""Book", says " . $this->getName();
        }
}
$aBook = new Poodle;
$aBook->Name = "PHP";
$aBook->say();
?>

上面的代码生成以下结果。

php的访问控制符有哪些

例子

下面的代码显示了如何使用Private成员隐藏信息。

<?php
  class Widget
  {
    private $name;
    private $price;
    private $id;
    public function __construct($name, $price)
    {
      $this->name = $name;
      $this->price = floatval($price);
      $this->id = uniqid();
    }
    //checks if two widgets are the same
    public function equals($widget)
    {
      return(($this->name == $widget->name) AND
       ($this->price == $widget->price));
    }
  }
  $w1 = new Widget("Cog", 5.00);
  $w2 = new Widget("Cog", 5.00);
  $w3 = new Widget("Gear", 7.00);
  //TRUE
  if($w1->equals($w2))
  {
    print("w1 and w2 are the same<br>\n");
  }
  //FALSE
  if($w1->equals($w3))
  {
    print("w1 and w3 are the same<br>\n");
  }
  //FALSE, == includes id in comparison
  if($w1 == $w2)
  {
    print("w1 and w2 are the same<br>\n");
  }
?>

上面的代码生成以下结果。

php的访问控制符有哪些

返回顶部
顶部