实例化PHP类的对象的本地或全局作用域


Local or global scope for objects instantiating PHP classes?

当为网站编写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的每个范围的优点和缺点(如果有的话)是什么?

DI更好:^)

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

但这取决于…:^)