Markus
Markus

Reputation: 53

Best practice use global variables inside functions/classes or pass a variable by reference to a function?

What’s the best practice with PHP 5.6+? What is the more sparing method? Relating to resources / memory / speed.

Pass a variable by reference to a function. I don’t need to modify the variable:

$bigClass = new MyBigClass();

class MyClass extends AnotherClass
{
    protected $obj;

    function __construct(\namespace\interface &$obj) {
        $this->obj =& $obj;
    }

    public function function1() {
        $this->obj->doThings();
    }

    private function function2() {
        $this->obj->otherThings();
    }

    public function function3() {
        // and so on ...
    }
}

$my_class = new MyClass($bigClass);
// $my_class->...

or should I use the way with the global Keyword:

$bigClass = new MyBigClass();

class MyClass extends AnotherClass
{
    function __construct() { }

    public function function1() {
        global $bigClass;
        $bigClass->doThings();
    }

    private function function2() {
        global $bigClass;
        $bigClass->otherThings();
    }

    public function function3() {
        // and so on ...
    }
}

$my_class = new MyClass();
// $my_class->...

Which method consumes the most resources and is slow?

Or to be nothing to speak of?

Thanks

Upvotes: 0

Views: 360

Answers (1)

Devon Bessemer
Devon Bessemer

Reputation: 35337

Objects are already passed by reference. Here is a test script to show you:

<?php

class MyClass {
    public $value;
}

function test(MyClass $test) {
    $test->value = 2;
}

$class = new MyClass;
$class->value = 5;
test($class);

echo $class->value; // echoes 2

In general, I don't think you should worry about performance when dealing with references unless you have a massive variable. If you truly operate a web site close to the magnitude of Facebook, Amazon, or Google you may see the benefit from these micro-optimizations, but otherwise, it's going to be a waste of time.

Upvotes: 1

Related Questions