SplObjectStorage object storage of SPL

<?php
/**
 * Created by PhpStorm.
 * User: zrj
 * Date: 18-4-24
 * Time: 8:37 pm
 */

class Person
{
    public $name;

    public function __construct(string $name)
    {
        $this->name = $name;
    }
}

// instantiate the object
$zhangsan = new Person('Zhang San');
$lisi = new Person('Li Si');
$wangwu = new Person('Wangwu');
$zhaoliu = new Person('Zhao Liu');

//Instantiate object storage
$container = new SplObjectStorage();

//Write object to storage space
$container->attach($zhangsan);
$container->attach($lisi);
$container->attach($wangwu);
$container->attach($zhaoliu);

// Count the number of objects in the storage space
echo "Number of objects stored" . $container->count();
echo "<br/>";

/ / Determine whether the specified object is in the storage space
echo "Does it contain the specified object:";
var_dump($container->contains($lisi));
echo "<br/>";

// delete the specified object from storage
echo "delete the specified object";
$container->detach($wangwu);

//View the index position of the current pointer
echo "pointer index" . $container->key();
echo "<br/>";

// reset the storage space pointer
$container->rewind();

//Check if the current pointer is valid
var_dump($container->valid());


// Traverse the storage space
echo "<pre>";
while ($container->valid()) {

    //Get the object at the current pointer position
    var_dump($container->current());

    //move the storage space pointer down
    $container->next();
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324847381&siteId=291194637