Programster's Blog

Tutorials focusing on Linux, programming, and open-source

PHP - Callbacks And Sharing Resources

PHP

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
Last updated: 16th September 2021
First published: 16th August 2018

This blog is created by Stuart Page

I'm a freelance web developer and technology consultant based in Surrey, UK, with over 10 years experience in web development, DevOps, Linux Administration, and IT solutions.

Need support with your infrastructure or web services?

Get in touch