【问题标题】:Local or global scope for objects instantiating PHP classes?实例化 PHP 类的对象的本地或全局范围?
【发布时间】:2014-04-10 08:58:55
【问题描述】:

在为网站编写 PHP 代码时,什么更好:

<?php

  include ("myclass.php");
  $theClass = new MyClass();

  function x () {
    global $theClass;
    $theClass->theProperty="foo";
    $theClass->doStuff();
  }

  function y () {
    global $theClass;
    $theClass->theProperty="bar";
    $theClass->doStuff();form
  }

?>

或:

<?php

  include ("myclass.php");

  function x () {
    $theClass = new MyClass();
    $theClass->theProperty="foo";
    $theClass->doStuff ();
  }

  function y () {
    $theClass = new MyClass();
    $theClass->theProperty="bar";
    $theClass->doStuff ();
  }

?>

对于$theClass的每个范围,上述哪一项更可取,如果有的话,有哪些优点和缺点?

【问题讨论】:

    标签: php class object scope


    【解决方案1】:

    更好的是DI :^)

      include ("myclass.php");
    
      function x (\MyClass $theClass) {
        $theClass->theProperty="foo";
        $theClass->doStuff ();
      }
    
      function y (\MyClass $theClass) {
        $theClass->theProperty="bar";
        $theClass->doStuff ();
      }
    

    但这取决于... :^)

    【讨论】:

    • 关于作用域,为什么DI比OP中的第二个sn-p好?
    • 例如,@FrankvanWensveen。今天我不得不继承DateInterval 来添加新方法。但是我失败了,因为$date_time1-&gt;diff($date_time2);中的依赖没有倒置
    猜你喜欢
    • 2012-07-28
    • 2021-03-05
    • 2014-11-28
    • 1970-01-01
    • 2013-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多