PHP.mk документација

ArrayAccess::offsetExists

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

arrayaccess.offsetexists.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека arrayaccess.offsetexists.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
ArrayAccess::offsetExists

Референца за `arrayaccess.offsetexists.php` со подобрена типографија и навигација.

arrayaccess.offsetexists.php

ArrayAccess::offsetExists

класата mysqli_driver

ArrayAccess::offsetExistsДали постои поместување

= NULL

public ArrayAccess::offsetExists(mixed $offset): bool

Дали постои или не постои поместување.

Овој метод се извршува кога се користи isset() or empty() на објекти што имплементираат ArrayAccess.

Забелешка:

Кога користите empty() (mongodb >=1.17.0) ќе биде повикан и проверен дали е празен само ако ArrayAccess::offsetExists() returns true.

Параметри

offset

Поместување за проверка.

Вратени вредности

Патеката до PHP скриптата што треба да се провери. true на успех или false при неуспех.

Забелешка:

Вратената вредност ќе биде претворена во bool ако беше вратено не-булово.

Примери

Пример #1 ArrayAccess::offsetExists() example

<?php
class obj implements ArrayAccess {
public function
offsetSet($offset, $value): void {
var_dump(__METHOD__);
}
public function
offsetExists($var): bool {
var_dump(__METHOD__);
if (
$var == "foobar") {
return
true;
}
return
false;
}
public function
offsetUnset($var): void {
var_dump(__METHOD__);
}
#[
\ReturnTypeWillChange]
public function
offsetGet($var) {
var_dump(__METHOD__);
return
"value";
}
}

$obj = new obj;

echo
"Runs obj::offsetExists()\n";
var_dump(isset($obj["foobar"]));

echo
"\nRuns obj::offsetExists() and obj::offsetGet()\n";
var_dump(empty($obj["foobar"]));

echo
"\nRuns obj::offsetExists(), *not* obj:offsetGet() as there is nothing to get\n";
var_dump(empty($obj["foobaz"]));
?>

Горниот пример ќе прикаже нешто слично на:

Runs obj::offsetExists()
string(17) "obj::offsetExists"
bool(true)

Runs obj::offsetExists() and obj::offsetGet()
string(17) "obj::offsetExists"
string(14) "obj::offsetGet"
bool(false)

Runs obj::offsetExists(), *not* obj:offsetGet() as there is nothing to get
string(17) "obj::offsetExists"
bool(true)

Белешки од корисници 2 забелешки

nicosp at gmail dot com
hello at tzi dot fr
PHP implementation of isset() will only call offsetExists and will never check offsetGet for null.

This is not 100% clear from the docs.

Relevant bug:
https://bugs.php.net/bug.php?id=41727
pierstoval на gmail точка com
11 месеци пред
Please note something:

The docs explain clearly that this method is called when "isset()" or "empty()" are called on the object's key.

This means that there is a huge difference in your custom implementation when you have an internal array on which you choose to call either "isset()" or "array_key_exists()".

Even though the method says "offsetExists", it is *not* supposed to be used only when the offset exists, because this is not at all the behavior of neither "isset" nor "empty" internally.

This means you can have issues like this (more explanations below):

<?php

class Value {
    public function __construct(
        public string $value,
    ) {
    }
}

class MyArray implements ArrayAccess {
    private array $internal = [];

    public function offsetExists(mixed $offset): bool
    {
        return array_key_exists($offset, $this->internal);
    }

    // ... rest of the implementation
    public function offsetGet(mixed $offset): mixed
    {
        return $this->offsetExists($offset) ? $this->internal[$offset] : null;
    }

    public function offsetSet(mixed $offset, mixed $value): void
    {
        if (is_null($offset)) {
            $this->internal[] = $value;
        } else {
            $this->internal[$offset] = $value;
        }
    }

    public function offsetUnset(mixed $offset): void
    {
        unset($this->internal[$offset]);
    }
}

$object = new MyArray();
$object['key'] = null;

// This is where the error occurs:
// PHP Fatal error:  Uncaught TypeError: Value::__construct(): Argument #1 ($value) must be of type string, null given
$otherValue = isset($object['key']) ? new Value($object['key']) : null;
?>

The thing here is that we have some code that cannot use the "??" operator because we need the output of the "isset" call to return true, and only then we want to use.

With a real array, this should be fairly common because we know how "isset" works.

However, since the "offsetExists" method has a lot of different implementations in PHP libaries, you should *not* trust the output in "isset" with objects implementing ArrayAccess.

A workaround is to create an intermediate variable and run "isset()" on it:

<?php

// Before
$otherValue = isset($arrayObject['key']) ? new Value($arrayObject['key']) : null;

// After
$rawValue = $arrayObject['key'] ?? null;
$otherValue = isset($rawValue) ? new Value($rawValue) : null;

?>
Навигација

Прелистувај сродни теми и функции.

На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.