dongmei6426 2016-12-23 15:15
浏览 61
已采纳

最佳实践在函数/类中使用全局变量或通过引用函数传递变量?

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(
amespace\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

  • 写回答

1条回答 默认 最新

  • douxiong2001 2016-12-23 15:38
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!