Detailed code explanation of the ArrayAccess interface in php

伊谢尔伦
Release: 2023-03-11 22:00:02
Original
1504 people have browsed it

The dependency injection in slim is based on pimple, so I went to learn pimple again. Compared with the dependency injection class I wrote before, pimple has a very new usage. Instead of using

$container->session_storage = function ($c) {
    return new $c['session_storage_class']($c['cookie_name']);
};
Copy after login

, it is injected in an array:

$container['session_storage'] = function ($c) {
    return new $c['session_storage_class']($c['cookie_name']);
};
Copy after login

When I looked at the source code, I realized that the trick is On the ArrayAccess interface provided by php5.
Official definition: An interface that provides the ability to access objects like accessing arrays.
This interface mainly defines four abstract methods:

abstract public boolean offsetExists ( mixed $offset ) #检查数据是否存在
abstract public mixed offsetGet ( mixed $offset )      #获取数据
abstract public void offsetSet ( mixed $offset , mixed $value )     #设置数据   
abstract public void offsetUnset ( mixed $offset ) #删除数据
Copy after login

If you want the object to be used like a PHP array, then we need to implement ArrayAccess Interface

The code is as follows:

interface ArrayAccess 
boolean offsetExists($index) 
mixed offsetGet($index) 
void offsetSet($index, $newvalue) 
void offsetUnset($index)
Copy after login


The following example shows how to use this interface. The example is not complete, but it is enough to understand, :->

The code is as follows:

<?php 
class UserToSocialSecurity implements ArrayAccess 
{ 
private $db;//一个包含着数据库访问方法的对象 
function offsetExists($name) 
{ 
return
 $this->db->userExists($name); 
} 
function offsetGet($name) 
{ 
return $this->db->getUserId($name); 
} 
function offsetSet($name, $id) 
{ 
$this->db->setUserId($name, $id); 
} 
function offsetUnset($name) 
{ 
$this->db->removeUser($name); 
} 
} 
$userMap = new UserToSocialSecurity(); 
print "John&#39;s ID number is " . $userMap[&#39;John&#39;]; 
?>
Copy after login


In fact, when the $userMap['John'] search is executed, PHP calls the offsetGet() method, which is then called Database-related getUserId() method.

The above is the detailed content of Detailed code explanation of the ArrayAccess interface in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!