ArrayAccess interface introduction

xiaoxiao2021-03-05  24

A series of new interfaces in PHP5. You can learn about their app in haohappy. At the same time, these interfaces and some implementation CLASS are classified as Standard PHP Library (SPL). Many characteristics have been added to PHP5 to make the overloading of the class receive further strengthen. The role of ArrayAccess is to make your class look like an array (PHP array). This index characteristic of this and C # is very similar. Here is the definition of ArrayAccess:

Interface ArrayAccessBoolean OffsetExists ($ INDEX) Mixed Offsetget ($ INDEX) VOID OFFSETSET ($ INDEX, $ NewValue) Void Offsetunset ($ index)

Due to the power of the array of PHP, many people often save the configuration information in an array when writing PHP applications. So maybe in the code is Global. We change ways? As follows:

// Configuration Class class Configuration implements ArrayAccess {static private $ config; private $ configarray; private function __construct () {// init $ this-> configarray = array ( "Binzy" => "Male", "Jasmin" => " "} Public static function instance () {// if (self: $ config == null) {self: $ config = new configuration ();} return self: $ config;} function offsetexists ($ Index) {RETURN ISSET ($ I-> ConfigArray [$ INDEX]);} Function Offsetget ($ index) {Return $ this-> configArray [$ index];} Function OffsetSet ($ INDEX, $ NewValue) {$ this- > configArray [$ index] = $ newValue;} Function offsetunset ($ index) {unset ($ this-> configArray [$ index]);}} $ config = configuration :: instance (); Print $ config ["binzy" ];

As you expected, the output of the program is "Male". If we do the following action:

$ config = configuration :: instance (); Print $ config ["binzy"]; $ config ['jasmin'] = "binzy's lover"; // config 2 $ config2 = configuration :: instance (); Print $ config2 [@ Config2 [ 'Jasmin'];

转载请注明原文地址:https://www.9cbs.com/read-32143.html

New Post(0)