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.

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

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退