PHP 类的一些知识点详解

jerry PHP 2015年11月15日 收藏

1.类的定义

  1. <?php
  2. class Cart{
  3.    var $items;
  4.    function add_item($artnr,$num){
  5.       $this->items[$artnr += $num;
  6.    }
  7. }

不能将一个类分开定义在多个文件,也不能将类定义分到多个PHP块(函数内部可以分)。

不能定义名为以下的类:

stdClass

__sleep

__wakeup

事实上不要以__开头定义类。

2.构造函数

  1. class Cart {
  2.     var $todays_date;
  3.     var $name;
  4.     var $owner;
  5.     var $items = array("VCR", "TV");
  6.     function Cart() {
  7.         $this->todays_date = date("Y-m-d");
  8.         $this->name = $GLOBALS['firstname'];
  9.         /* etc. . . */
  10.     }
  11. }

类如果没有构造函数,将调用基类构造函数。

构造函数参数可以赋默认值

  1. <?php
  2. class Constructor_Cart extends Cart {
  3.     function Constructor_Cart($item = "10", $num = 1) {
  4.         $this->add_item ($item, $num);
  5.     }
  6. }
  7. // 买些同样的无聊老货
  8. $default_cart = new Constructor_Cart;
  9. // 买些实在货...
  10. $different_cart = new Constructor_Cart("20", 17);
  11. ?>

@new 可以抑制发生在构造函数中的错误。

3.类的使用

  1. $cart = new Cart;
  2. $cart->add_item("10", 1);

类内部使用$this代表自身。

4.类相关函数

__autoload — 尝试加载未定义的类

call_user_method_array — 调用一个用户方法,同时传递参数数组(已废弃)

call_user_method — 对特定对象调用用户方法(已废弃)

class_alias — 为一个类创建别名

class_exists — 检查类是否已定义

get_called_class — 后期静态绑定(”Late Static Binding”)类的名称

get_class_methods — 返回由类的方法名组成的数组

get_class_vars — 返回由类的默认属性组成的数组

get_class — 返回对象的类名

get_declared_classes — 返回由已定义类的名字所组成的数组

get_declared_interfaces — 返回一个数组包含所有已声明的接口

get_declared_traits — 返回所有已定义的 traits 的数组

get_object_vars — 返回由对象属性组成的关联数组

get_parent_class — 返回对象或类的父类名

interface_exists — 检查接口是否已被定义

is_a — 如果对象属于该类或该类是此对象的父类则返回 TRUE

is_subclass_of — 如果此对象是该类的子类,则返回 TRUE

method_exists — 检查类的方法是否存在

property_exists — 检查对象或类是否具有该属性

trait_exists — 检查指定的 trait 是否存在

5.继承

  1. <?php
  2. class Named_Cart extends Cart {
  3.     var $owner;
  4.     function set_owner ($name) {
  5.         $this->owner = $name;
  6.     }
  7. }
  8. ?>

PHP不支持多继承。

6.静态方法

  1. <?php
  2. class A {
  3.     function example() {
  4.         echo "I am the original function A::example().<br />\n";
  5.     }
  6. }
  7. class B extends A {
  8.     function example() {
  9.         echo "I am the redefined function B::example().<br />\n";
  10.         A::example();
  11.     }
  12. }
  13. // A 类没有对象,这将输出
  14. //   I am the original function A::example().<br />
  15. A::example();
  16. // 建立一个 B 类的对象
  17. $b = new B;
  18. // 这将输出
  19. //   I am the redefined function B::example().<br />
  20. //   I am the original function A::example().<br />
  21. $b->example();
  22. ?>

7.基类引用 parent

  1. <?php
  2. class A {
  3.     function example() {
  4.         echo "I am A::example() and provide basic functionality.<br />\n";
  5.     }
  6. }
  7. class B extends A {
  8.     function example() {
  9.         echo "I am B::example() and provide additional functionality.<br />\n";
  10.         parent::example();
  11.     }
  12. }
  13. $b = new B;
  14. // 这将调用 B::example(),而它会去调用 A::example()。
  15. $b->example();
  16. ?>

8.序列化

  1. <?php
  2. // classa.inc:
  3.   class A {
  4.       var $one = 1;
  5.       function show_one() {
  6.           echo $this->one;
  7.       }
  8.   }
  9. // page1.php:
  10.   include("classa.inc");
  11.   $a = new A;
  12.   $s = serialize($a);
  13.   // 将 $s 存放在某处使 page2.php 能够找到
  14.   $fp = fopen("store", "w");
  15.   fwrite($fp, $s);
  16.   fclose($fp);
  17. // page2.php:
  18.   // 为了正常解序列化需要这一行
  19.   include("classa.inc");
  20.   $s = implode("", @file("store"));
  21.   $a = unserialize($s);
  22.   // 现在可以用 $a 对象的 show_one() 函数了
  23.   $a->show_one();
  24. ?>

9.魔术函数 __sleep __wakeup

10.允许数组方式访问对象属性

方法1

  1. function obj2array(obj){  
  2.  return new ArrayObject(obj, ArrayObject::ARRAY_AS_PROPS);
  3. }

这个方法比较简单,另一个方法要继承ArrayAccess要复杂一点。

11.数组转对象

  1. /**
  2.      * 数组转对象
  3.      * @param unknown $e
  4.      * @return void|StdClass
  5.      */
  6.     public static function arrayToObject($e){
  7.         if( gettype($e)!='array' ) return;
  8.         foreach($e as $k=>$v){
  9.             if( gettype($v)=='array' || getType($v)=='object' )
  10.                 $e[$k]=(object)arrayToObject($v);
  11.         }
  12.         return (object)$e;
  13.     }

12 自己实现的序列化与反序列化

用在redis时比较方便:

  1. /**
  2.      * 序列化对象,返回$json字符串
  3.      */
  4.     public static function serialize($model){
  5.         //return serialize($model);
  6.         if(!$model)return '{}';
  7.         $json='{';
  8.         foreach($model as $key2=>$value2){
  9.             if($json!='{')$json.=',';
  10.             $json.="$key2:\"$value2\"";
  11.         }
  12.         $json.='}';
  13.         return $json;
  14.     }
  15.     public static function unserialize($json){
  16.         $json=str_replace('{', '', $json);
  17.         $json=str_replace('}','',$json);
  18.         $array=explode(',', $json);
  19.         $result=[];
  20.         foreach($array as $key =>$value){
  21.             $temparr=explode(',',$value);
  22.             $temparr1=explode(':',$temparr[0]);
  23.             if(count($temparr1)==0)continue;
  24.             $result[$temparr1[0]]=trim( $temparr1[1],'"');
  25.         }
  26.         //$obj=  (object)($result);
  27.         return obj2array($result);
  28.         //return $result;
  29.     }