PHP code example of iddqdby / weak-array

1. Go to this page and download the library: Download iddqdby/weak-array library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

iddqdby / weak-array example snippets


$weak_array = new WeakArray\WeakArray();

$foo = new stdClass();
$bar = new stdClass();
$baz = new stdClass();

$weak_array['foo'] = $foo;
$weak_array['bar'] = $bar;
$weak_array['baz'] = $baz;

var_export($weak_array['foo']);
echo "\n";

var_export($weak_array['bar']);
echo "\n";

var_export($weak_array['baz']);
echo "\n";

echo "====\n";

unset($foo);
unset($bar);

var_export($weak_array['foo']);
echo "\n";

var_export($weak_array['bar']);
echo "\n";

var_export($weak_array['baz']);
echo "\n";

class Observer implements \SplObserver {
    public function update(\SplSubject $event) {
        // $event instanceof WeakArray\Event;
        // see WeakArray\Event class to view all available methods and Event::* constants
        switch ($event->getType()) {
            case WeakArray\Event::OBJECT_SET:
                $event_str = 'set';
                break;
            case WeakArray\Event::OBJECT_UNSET:
                $event_str = 'unset';
                break;
            case WeakArray\Event::OBJECT_DESTRUCTED:
                $event_str = 'destructed';
                break;
        }
        printf("Object %s, key %s\n", $event_str, $event->getKey());
    }
}

$weak_array = new WeakArray\WeakArray();
$observer = new Observer();

$weak_array->attach($observer);

$foo = new stdClass();
$bar = new stdClass();
$baz = new stdClass();

$weak_array['foo'] = $foo;
$weak_array['bar'] = $bar;
$weak_array['baz'] = $baz;

unset($foo);

unset($weak_array['bar']);
unset($weak_array['baz']);