Reputation: 787
The below is example2 from php.net's splobjectstorage documentation. The lines using $s[$o1] and $s[$o2] is syntax I'm not familiar with and haven't seen yet for objects (still learning)
Is this a standard way of fetching properties from an object that would work with any class I've created?
Is this instead using a magic method or additional programmed functionality to create this syntax for just this class?
<?php
// As a map from objects to data
$s = new SplObjectStorage();
$o1 = new StdClass;
$o2 = new StdClass;
$o3 = new StdClass;
$s[$o1] = "data for object 1";
$s[$o2] = array(1,2,3);
if (isset($s[$o2])) {
var_dump($s[$o2]);
}
?>
http://php.net/manual/en/class.splobjectstorage.php
Upvotes: 1
Views: 344
Reputation: 1944
The "square bracket" [ ]
syntax is an example of using SplObjectStorage
as a data map. Means, as a key->value store
.
The "key" of an element ($o1
, $o2
) in the SplObjectStorage is in fact the hash of the object. It makes it that, it is not possible to add multiple copies of the same object instance to an SplObjectStorage, so you don't have to check if a copy already exists before adding.
$o1
, $o2
can be any custom PHP class that you created. SplObjectStorage will take care the data mapping.
Normally, this 'square bracket' syntax is not used with Objects in PHP. It's used only with arrays.
While working with objects, use the $object->property
or $object->function()
syntax.
Courtesy:
Upvotes: 2
Reputation: 38014
You can use the square bracket syntax for arrays and all classes that implement the ArrayAccess
interface (which SplObjectStorage
does).
Example:
class MyObjectStorage implements ArrayAccess {
public function offsetExists($offset) {}
public function offsetSet($offset, $value) {
echo "Set $offset to $value.";
}
public function offsetGet($offset) {
echo "Get $offset.";
}
public function offsetUnset($offset) {}
}
$list = new MyObjectStorage();
$list['foo'] = 'bar'; // prints "Set foo to bar.";
See http://php.net/ArrayAccess for more information.
Upvotes: 1