My life be like

Learning new things in PHP

“I love learning new little things” Published at: 2019-01-08

I have been developing PHP applications for a little over 3 years now. I don’t think I am experienced at all but I can manage. Sometimes I still come across things I find most interesting. Today I learned that return values are returned by value, not by reference.

I had a function which returned a property that was an array. I tried to append the array but after printing the array. I have an example below.

<?php
class Foo {
    public $select: [];

    public function getSelect() {
        return $this->select;
    }
}

$foo: new Foo();

$foo->getSelect()[]: 'bar';

var_dump($foo->getSelect()); // returns []

$foo->select[]: 'bar';

var_dump($foo->getSelect()); // return ['bar']

So when a value is returned the value is returned and not the reference. So you can’t use the reference after returning it. You can return the reference when using the & character in PHP. Change the method to public function &getSelect() makes sure that a reference is returned.


This is the first time I have encountered this. It’s not an issue but a design choice of PHP. You fail and you learn.

Oscar te Giffel

Oscar te Giffel. I wan't to learn so many things. This is just my journey through life.