1
2
3
4
5
6
7
8
|
接口摘要
ArrayAccess {
/* 方法 */
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
)
}
|
举个例子
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
class
Test
implements
ArrayAccess
{
private
$testData
= [];
public
function
offsetExists(
$offset
)
{
echo
'call '
.
__METHOD__
.
"\r\n"
;
return
isset(
$this
->testData[
$offset
]);
}
public
function
offsetGet(
$offset
)
{
echo
'call '
.
__METHOD__
.
"\r\n"
;
return
$this
->testData[
$offset
];
}
public
function
offsetSet(
$offset
,
$value
)
{
echo
'call '
.
__METHOD__
.
"\r\n"
;
return
$this
->testData[
$offset
] =
$value
;
}
public
function
offsetUnset(
$offset
)
{
echo
'call '
.
__METHOD__
.
"\r\n"
;
unset(
$this
->testData[
$offset
]);
}
}
|
$obj = new Test();
if (!isset($obj['name'])) { //call Test::offsetExists
$obj['name'] = 'zhangsan'; //call Test::offsetSet
}
echo $obj['name'] . "\r\n"; //call Test::offsetGet
var_dump($obj);
$obj['age'] = 18; //call Test::offsetSet
echo $obj['age'] . "\r\n"; //call Test::offsetGet
unset($obj['address']); //call Test::offsetUnset
本文转自 hgditren 51CTO博客,原文链接:http://blog.51cto.com/phpme/2044625,如需转载请自行联系原作者