略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: ArrayObject::offsetGet

2024-11-15

ArrayObject::offsetGet

(PHP 5, PHP 7, PHP 8)

ArrayObject::offsetGetReturns the value at the specified index

说明

public ArrayObject::offsetGet(mixed $key): mixed

参数

key

The index with the value.

返回值

The value at the specified index or null.

错误/异常

Produces an E_NOTICE error message when the specified index does not exist.

范例

示例 #1 ArrayObject::offsetGet() example

<?php
$arrayobj 
= new ArrayObject(array('zero'7'example'=>'e.g.'));
var_dump($arrayobj->offsetGet(1));
var_dump($arrayobj->offsetGet('example'));
var_dump($arrayobj->offsetExists('notfound'));
?>

以上例程会输出:

int(7)
string(4) "e.g."
bool(false)
add a noteadd a note

User Contributed Notes 3 notes

up
3
Jason
6 years ago
It's worth noting that the PHP devs *did* fix the issue brought up in Sam's comment in 2013 (per the comment thread in his link here: https://bugs.php.net/bug.php?id=34783#1366088374), since at least PHP 5.3.8.

So, you *can* (and in most cases should) overload offsetGet with reference syntax to get expected functionality:

<?php
class myArrayType extends ArrayAccess {

    public function &
offsetGet($index) {
       
// ...
   
}

}
?>
up
4
Sam
14 years ago
If you're overloading ArrayObject, it's worth noting that while this method (when implemented by the parent) will return a reference, so code like $fakeArray['foobar']['hello'] = 1; will work like you expect.

However, when you overload the offsetGet method, you CANNOT define it as &offsetGet, so the above code falls out (because it returns the 'foobar' variable before you actually work with it).

This is something that the developers broke between 5.0 and 5.1, and was closed as bogus (http://bugs.php.net/bug.php?id=34783). So this is not a big, or question, or request, but just something worth noting.
up
1
Alex Andrienko
13 years ago
Speaking of offsetGet() method overloading, be advised, that if you're iterating through Object via foreach, this method wouldn't be called. Iterator's current() method will be called instead.

官方地址:https://www.php.net/manual/en/arrayobject.offsetget.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3