PHP pre-defined interface arrayaccess,php scheduled arrayaccess_php tutorial

Source: Internet
Author: User

PHP pre-defined interface arrayaccess,php scheduled arrayaccess


Recently this time to go home for the New Year, blog has not been updated, feel less learning a lot of things, also missed a lot of learning opportunities, like everyone in the Spring Festival to rob Red envelopes often said a sentence: A not careful missed a good hundreds of millions of. Needless to say, this blog to everyone about the PHP pre-defined interface commonly used in the heavyweight characters: Arrayaccess. You may ask, the most basic, most commonly used pre-defined interface has 6, why must say this. From the daily use of the situation: the frequency is very high, especially in the framework, such as Laravel, Slim and so will be used, and used very classic, let people admire ah. Technically: Honestly, the rest of me uses less! Just know simple usage, the understanding of him is more superficial, dare not mislead everyone here, haha! What I am going to write today is not necessarily correct, please correct me.

arrayaccess

Say Arrayaccess first! The role of arrayaccess is to make your objects accessible like arrays. It should be said that arrayaccess in the PHP5 only began to have, PHP5 added a lot of new features, of course, also make the overload of the class also strengthened, PHP5 added a series of interfaces, these interfaces and the implementation of the class collectively known as SPL.

Arrayaccess This interface defines 4 methods that must be implemented:

1 {2    Abstract  public offsetexists ($offset)  // Check if offset position exists 3     Abstract public offsetget ($offset)     // Get the value of an offset position 4     Abstract public void Offsetset ($offset ,$value//  Sets the value of an offset position 5    abstract public void Offsetunset ($offset )       // Reset the value of an offset position 6 }

So we want to use arrayaccess this interface, we must implement the corresponding method, these methods are not casually written, we can look at the Arrayaccess prototype:

1 /**2 * Interface to provide accessing objects as arrays.3 * @link http://php.net/manual/en/class.arrayaccess.php4  */5 Interfacearrayaccess {6 7     /**8 * (PHP 5 >= 5.0.0)
9 * Whether a offset existsTen * @link http://php.net/manual/en/arrayaccess.offsetexists.php One * @param mixed $offset

a offset to check for. *

- * @return Boolean true on success or false on failure. the *

- *

* The return value is casted to a Boolean if Non-boolean was returned. - */ + Public function offsetexists ($offset); * * * (PHP 5 >= 5.0.0)
* Offset to retrieve * @link Http://php.net/manual/en/arrayaccess.off setget.php * @param mixed $offset

* The offset to retrieve. *

- * @return Mixed Can return all value types. in */ - Public functionOffsetget ($offset); to + /** - * (PHP 5 >= 5.0.0)
the * Offset to set * * @link http://php.net/manual/en/arrayaccess.offsetset.php $ * @param mixed $offset

PNS * The offset to assign the value to. *

the * @param mixed $value

* The value to set. *

the * @return void + */ - Public functionOffsetset ($offset,$value); $ $ /** - * (PHP 5 >= 5.0.0)
- * Offset to unset the * @link http://php.net/manual/en/arrayaccess.offsetunset.php - * @param mixed $offset

Wuyi * The offset to unset. *

- * @return void Wu */ - Public functionOffsetunset ($offset); About}

Here we can write an example, very simple:

1 
 Php2 classTestImplementsarrayaccess3 {4     Private $testData;5 6      Public functionOffsetexists ($key)7     {8         return isset($this->testdata[$key]);9     }Ten  One      Public functionOffsetset ($key,$value) A     { -         $this->testdata[$key] =$value; -     } the  -      Public functionOffsetget ($key) -     { -         return $this->testdata[$key]; +     } -  +      Public functionOffsetunset ($key) A     { at         unset($this->testdata[$key]); -     } - } -  -   $obj=NewTest (); -  in   //automatically call the Offsetset method - $obj[' data '] = ' data '; to  +   //Call offsetexists automatically - if(isset($obj[' Data '])){ the     Echo' Has setting! '; *   } $   //Call Offsetget automaticallyPanax Notoginseng   Var_dump($obj[' Data ']); -  the   //Call Offsetunset automatically +   unset($obj[' Data ']); A   Var_dump($test[' Data ']); the  +   //Output: -   //has setting! $   //data $   //null

Well, below we will combine the slim framework in the actual application, in the slim use is very important, also very good use of container,container inherited from Pimple\container, speaking of this, it is necessary to say pimple, Pimple is a popular IOC container in the PHP community, and the container class in Pimple uses a dependency injection approach to implement low-coupling between programs, which can be added with composer require "pimple/pimple": "1.*" Add pimple to the Dependency class library,pimple or to take a look at, just a file, in the program throughout the life cycle, various properties, methods, objects, closures can be registered, but pimple just implement a container concept, there are many dependency injection, automatic creation, Related functions need to see Laravel to learn deeply.

In slim it uses the container class to load the configuration files sequentially, accessing them like an array, including Displayerrordetails,renderer, Logger,httpversion, Responsechunksize,outputbuffering,determineroutebeforeappmiddleware,displayerrordetails and so on, so that they are loaded first when the framework is loaded. You can take it directly when you use it.

Here is the loading mechanism:

 Phpnamespace Slim; UseInterop\container\containerinterface; UseInterop\container\Exception\containerexception; UsePimple\container asPimplecontainer; UsePsr\http\message\responseinterface; UsePsr\http\message\serverrequestinterface; UseSlim\Exception\containervaluenotfoundexception;classContainerextendsPimplecontainerImplementscontainerinterface{/** * Default Settings * * @var array*/    Private $defaultSettings= [        ' Httpversion ' = ' 1.1 ', ' responsechunksize ' + 4096, ' outputbuffering ' = ' append ', ' Determi Neroutebeforeappmiddleware ' =false, ' displayerrordetails ' =false,    ]; /** * Create new container * * @param array $values the parameters or objects. */     Public function__construct (Array $values= [])    {        //Var_dump ($values); Exit;Parent::__construct ($values); $userSettings=isset($values[' Settings ']) ?$values[' Settings ']: []; $this->registerdefaultservices ($userSettings); }    Private functionRegisterdefaultservices ($userSettings)    {        $defaultSettings=$this-DefaultSettings; $this[' Settings '] =function() Use($userSettings,$defaultSettings) {            return NewCollection (Array_merge($defaultSettings,$userSettings));                }; $defaultProvider=NewDefaultservicesprovider (); $defaultProvider->register ($this); }      . . .}

Where defaultsettings is the system default configuration,usersettings for the user's configuration, such as logs, templates and so on.

The following paragraph is offsetget, smart use of key values to determine whether the value has been set, if set up will go directly to fetch, no setting will go to the logic of the setting.

1      Public functionOffsetget ($id)2     {3         if(!isset($this->keys[$id])) {4             Throw New\invalidargumentexception (sprintf(' Identifier '%s ' is not defined. ',$id));5         }6 7         if (8             isset($this->raw[$id])9|| !Is_object($this->values[$id])Ten||isset($this-protected[$this->values[$id]]) One|| !method_exists($this->values[$id], ' __invoke ') A         ) { -             return $this->values[$id]; -         } the  -         if(isset($this->factories[$this->values[$id]])) { -             return $this->values[$id]($this); -         } +  -         $raw=$this->values[$id]; +         $val=$this->values[$id] =$raw($this); A         $this->raw[$id] =$raw; at  -         $this->frozen[$id] =true; -  -         return $val; -}

Let's look at Pimplecontainer, for example:

We can see that there is a splobjectstorage, which needs to be said, Splobjectstorage is used to store a set of objects when you need to uniquely identify the object. According to the official website of the PHP SPL Splobjectstorage class implementation of countable, Iterator, Serializable, arrayaccess four interfaces, can achieve statistics, iteration, serialization, array-type access and other functions. So Splobjectstorage is a standard object container.

Speaking of this we should have some understanding of arrayaccess, if not clear, you can see more slim source code, the above written more clear, and that set of source code and its concise, it is worth learning.

Blog will be updated to my personal website, welcome to visit!

Reproduced please indicate the source, the following will continue to update, thank you!

http://www.bkjia.com/PHPjc/1104066.html www.bkjia.com true http://www.bkjia.com/PHPjc/1104066.html techarticle PHP pre-defined interface arrayaccess,php booking arrayaccess recently this time home for the New Year, blog has not been updated, feel less learning a lot of things, also missed a lot of learning opportunities ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.