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

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

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

图片转代码服务由CSDN问答提供 功能建议

PHP 5.6 +的最佳实践是什么? 什么是更节省的方法? 与资源/内存/速度有关。

通过引用函数传递变量。 我不需要修改变量:

  $ bigClass = new MyBigClass(); 
 
class MyClass扩展AnotherClass 
 {
 protected $ obj; 
  
 function __construct(
amespace \ interface& $ obj){
 $ this-> obj =&  $ obj; 
} 
 
公共函数function1(){
 $ this-> obj-> doThings(); 
} 
 
私有函数function2(){
 $ this-&gt  ; obj-> otherThings(); 
} 
 
公共函数function3(){
 //等等... 
} 
} 
 
 $ my_class = new MyClass($ bigClass)  ); 
 // $ my_class-> ... 
   
 
 

或者我应该使用全局关键字的方式:

  $ bigClass = new MyBigClass(); 
 
class MyClass扩展了AnotherClass 
 {
函数__construct(){} 
 
公共函数function1(){
 
 
 
 
全局$ bigClass; 
  $ bigClass-> doThings(); 
} 
 
私有函数function2(){
 global $ bigClass; 
 $ bigClass-> otherThings(); 
} 
 
公共函数function3(  ){
 //等等... 
} 
} 
 
 $ my_class = new MyClass(); 
 // $ my_class-> ... 
   
 
 

哪种方法消耗的资源最多而且速度慢?

或者无话可说?

谢谢

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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.

    打赏 评论

相关推荐 更多相似问题