PHP - Callbacks And Sharing Resources

Something I keep questioning myself on is whether use() passes instantiated classes by reference or creates a copy, and whether this applies to the stdClass as well.

The script below demonstrates that all objects (including stdClass) are passed by reference but basic types such as integers are passed a copy. This is especially useful to know when playing with callbacks where we need to retrieve values but can't utilize return for whatever reason.

<?php

$sharedResource = new stdClass();
$sharedResource->value = 1;
$integer = 1;

$callback2 = function() use($sharedResource, $integer)
{
    print "value: $sharedResource->value" . PHP_EOL;
    print "Integer value: $integer" . PHP_EOL;
};

$callback = function() use($sharedResource, $integer)
{
    $sharedResource->value = 3;
    $integer = 3;
};

$callback();
$callback2();

# Output:
# value: 3
# Integer value: 1

Normal functions act the same way (whereby objects are passed by reference), so be careful when passing objects as parameters as the function may alter them.

<?php

$sharedResource = new stdClass();
$sharedResource->value = 1;
$integer = 1;

function function2($sharedResource, $integer)
{
    print "value: $sharedResource->value" . PHP_EOL;
    print "Integer value: $integer" . PHP_EOL;
}

function function1($sharedResource, $integer)
{
    $sharedResource->value = 3;
    $integer = 3;
}


function1($sharedResource, $integer);
function2($sharedResource, $integer);

# Output:
# value: 3
# Integer value: 1

Author

Programster

Stuart is a software developer with a passion for Linux and open source projects.

comments powered by Disqus
We are a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for us to earn fees by linking to Amazon.com and affiliated sites. More info.