Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between SplObjectStorage::contains and SplObjectStorage::offsetExists?

The PHP documentation is not very explicit and only states that:

SplObjectStorage::offsetExists Checks whether an object exists in the storage. (PHP >= 5.3.0)

SplObjectStorage::contains Checks if the storage contains the object provided. (PHP >= 5.1.0)

Which pretty much seems the same thing to me.

QUESTION: Apart from offsetExists being only available in 5.3.0, what is the difference between the 2?


small test I conducted...

$s = new SplObjectStorage();
$o1 = new StdClass();
$o2 = new StdClass();
$o3 = "I'm not an object!";
$s->attach($o1);

var_dump($s->contains($o1));
var_dump($s->offsetExists($o1));
echo '<br>';
var_dump($s->contains($o2));
var_dump($s->offsetExists($o2));
echo '<br>';
var_dump($s->contains($o3));
var_dump($s->offsetExists($o3));

output:

boolean true
boolean true

boolean false
boolean false

Warning: SplObjectStorage::contains() expects parameter 1 to be object, string given in index.php on line 15
null

Warning: SplObjectStorage::offsetExists() expects parameter 1 to be object, string given in index.php on line 16
null
like image 764
Tivie Avatar asked Aug 16 '12 08:08

Tivie


1 Answers

They are both exactly the same.

offsetExists is defined as a method alias of contains and is included simply for compliance with the ArrayAccess interface.

You can see for yourself in the source that SPL_MA (method alias) is being used, and also that there are a couple of other aliases set up.

  • offsetExists = contains
  • offsetSet = attach
  • offsetUnset = detach
like image 141
Leigh Avatar answered Sep 30 '22 19:09

Leigh