php的面向对象:
1:类,对象,字段,方法:
<?php
class Computer{ //类的声明
private $_a; //字段的声明
public function a(){ //方法的声明
echo "string";
}
}
$_computer = new Computer(); //new 出一个对象
?>
2:字段的作用域:
public:公共的,类外可以访问;
private:私有的类内可以访问;
protected:受保护的,类内和子类可以访问。
3:私有字段的访问方法:
3.1:公共方法访问私有字段,访问私有方法:
<?php
class Computer{ //类的声明
private $_a = 1; //字段的声明
public function a(){ //通过公共方法访问私有变量
return $this->_ab;
}
}
$_computer = new Computer(); //new 出一个对象
echo $_computer->a();
?>
3.2:属性操作,私有字段的赋值与取值:拦截器;
<?php
class Computer{ //类的声明
private $_a = 1; //字段的声明
// 赋值
public function __set($_key,$_value){
$this->$_key = $_value;
}
// 取值
public function __get($_key,$_value){
return $this->$_key;
}
}
$_computer = new Computer(); //new 出一个对象
$_computer->a = 2; // 赋值
echo $_computer->a; // 取值
?>
4:常量,静态类;
<?php
class Computer{
const A = 1; //常量
private static $_a = 2; //静态字段
public static function get(){ //公共静态方法访问私有静态变量
return self::$_a;
}
}
echo Computer::A; //1
echo Computer::get(); //2
?>