实例化PHP类的对象的本地或全局范围?

时间:2014-04-10 08:58:55

标签: php class object scope

为网站编写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 的每个范围,上述哪一项更可取,哪些优缺点(如果有)?

1 个答案:

答案 0 :(得分:2)

更好的是DI:^)

  include ("myclass.php");

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

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

但这取决于......:^)