spl 教程四 接口


一 ArrayAccess 可以讓對象像數組一樣去使用


二 Countable 可以使count(對象) 與count(數組)一樣

 http://php.net/manual/en/class.arrayaccess.php


    class SplAccess implements  ArrayAccess, Countable
    {
        private  $data =[];


        public function __construct($data){

            $this ->data = $data ;

        }
        public function offsetExists($offset){
            echo "offsetExists".PHP_EOL ;
            return isset($this->data[$offset]);
        }

        public function offsetGet($offset){
            echo "offsetGet".PHP_EOL ;
            print_r($this->data);
            return $this->data[$offset] ;
        }

        public function offsetSet($offset, $value){
            echo "offsetSet" .PHP_EOL;
            $this->data[$offset] = $value ;
        }

        public function offsetUnset($offset){
            echo "offsetUnset" .PHP_EOL;
            unset($this->data[$offset]);
        }

        public function count(){
            echo "count" .PHP_EOL;
            return count($this->data);
        }
    }

    $data =[
        'a'  => 'wlt' ,
        'c'  => 1 ,
        'd'  => 1 ,
        'e'  => 1 ,
    ] ;
    $obj = new SplAccess($data);



    //    執行offsetSet 方法
//    $obj['a'] = 2;
//    執行offsetget 方法
    echo $obj['a'] ;
//    執行offsetExists 方法
   $t = isset($obj['a']) ;
// 執行 offsetUnset 方法
 unset($obj['a']) ;
//    執行count方法
echo count($obj) ;


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章