Note that even though isset/empty works on classes implementing ArrayAccess, array_key_exists does not. At least not in PHP 5.3.
(PHP 5, PHP 7)
ArrayAccess::offsetExists — Sprawdza czy offset istnieje
Sprawdza czy offset istnieje.
Ta metoda jest wykonywana gdy użyto isset() lub empty() na obiektach implementujących ArrayAccess.
Informacja:
Przy użyciu empty() ArrayAccess::offsetGet() zostanie wywołane i sprawdzone czy jest puste, tylko jeśli ArrayAccess::offsetExists() zwróci
TRUE
.
offset
Offset do sprawdzenia.
Zwraca TRUE
w przypadku powodzenia, FALSE
w
przypadku błędu.
Informacja:
Zwracana wartość zostanie skonwertowana do typu boolean, jeżeli została zwrócona inna.
Przykład #1 Przykład użycia ArrayAccess::offsetExists()
<?php
class obj implements arrayaccess {
public function offsetSet($offset, $value) {
var_dump(__METHOD__);
}
public function offsetExists($var) {
var_dump(__METHOD__);
if ($var == "foobar") {
return true;
}
return false;
}
public function offsetUnset($var) {
var_dump(__METHOD__);
}
public function offsetGet($var) {
var_dump(__METHOD__);
return "wartość";
}
}
$obj = new obj;
echo "Wykonuje obj::offsetExists()\n";
var_dump(isset($obj["foobar"]));
echo "\nWykonuje obj::offsetExists() i obj::offsetGet()\n";
var_dump(empty($obj["foobar"]));
echo "\nWykonuje obj::offsetExists(), *nie* obj:offsetGet(), gdyż nie ma nic do pobrania\n";
var_dump(empty($obj["foobaz"]));
?>
Powyższy przykład wyświetli coś podobnego do:
Wykonuje obj::offsetExists() string(17) "obj::offsetExists" bool(true) Wykonuje obj::offsetExists() and obj::offsetGet() string(17) "obj::offsetExists" string(14) "obj::offsetGet" bool(false) Wykonuje obj::offsetExists(), *nie* obj:offsetGet(), gdyż nie ma nic do pobrania string(17) "obj::offsetExists" bool(true)
Note that even though isset/empty works on classes implementing ArrayAccess, array_key_exists does not. At least not in PHP 5.3.
It seems that in PHP 7, if this method returns FALSE then offsetGet() will return NULL (in PHP 5, offsetGet() didn't first check what value offsetExists() returned). So if your code suddenly stops working when you upgrade to PHP 7 make sure that offsetExists() returns a sensible value!
If you care about key-strictness, you may need to use an alternative solution (maybe overriding offsetExists() in subclass(es)). So, offsetExists() acts like array_key_exists() and does not handle the key types. Here;
<?php
$array = ['one', 'two', 3.=>'boom!'];
$arrayObject = new ArrayObject($array);
$key = '3';
var_dump(array_key_exists($key, $array)); // bool(true)
var_dump(in_array($key, array_keys($array), true)); // bool(false)
var_dump($arrayObject->offsetExists($key)); // bool(true)
var_dump(in_array($key, array_keys($arrayObject->getArrayCopy()), true)); // bool(false)
// @override;
public function offsetExists($key)
{
// make a strict check
return in_array($key, array_keys($this->getArrayCopy()), true);
}
?>