class Person
{
static $type = 'person';
const TYPE = 'person';
static public function getType(){
var_dump(self::TYPE);
var_dump(static::TYPE);
var_dump(self::$type);
var_dump(static::$type);
}
}
class Pirate extends Person
{
static $type = 'pirate';
const TYPE = 'pirate';
}
从 PHP 5.3.0开始,可以使用变量引用该类。变量的值不能是关键字(例如 self、 father 和 static)。
静态属性示例
<?php
class Foo
{
public static $my_static = 'foo'; //static variable
public static function staticValue() { //static function example
return self::$my_static; //return the static variable declared globally
}
}
?>
使用私有的、公共的、受保护的关键字,您可以控制对类中成员的访问。声明为 public 的类成员可以在任何地方访问。声明受保护的成员只能在类本身以及继承类和父类中访问。声明为 private 的成员只能由定义该成员的类访问。
例子
<?php
class Example{
public $variable = 'value'; // variable declared as public
protected $variable = 'value' //variable declared as protected
private $variable = 'value' //variable declared as private
public function functionName() { //public function
//statements
}
protected function functionName() { //protected function
//statements
}
private function functionName() { //private function
//statements
}
}
?>
访问公共、私有和受保护成员的示例
可以从类外部访问和修改公共变量
或者在教室里。但是只能从类内部访问私有和受保护的变量和函数,不能在类外部修改 protected 或 Public 成员的值。
<?php
class Example{
public $pbVariable = 'value';
protected $protVariable = 'value';
private $privVariable = 'value';
public function publicFun(){
echo $this->$pbVariable; //public variable
echo $this->$protVariable; //protected variable
echo $this->privVariable; //private variable
}
private function PrivateFun(){
//some statements
}
protected function ProtectedFun(){
//some statements
}
}
$inst = new Example();
$inst->pbVariable = 'AnotherVariable'; //public variable modifed from outside
echo $inst->pbVariable; //print the value of the public variable
$inst->protVariable = 'var'; //you can't do this with protected variable
echo $inst->privVariable; // This statement won't work , because variable is limited to private
$inst->publicFun(); // this will print the values inside the function, Because the function is declared as a public function
$inst->PrivateFun(); //this one won't work (private)
$inst->ProtectedFun(); //this one won't work as well (protected)
?>