为网站编写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 的每个范围,上述哪一项更可取,哪些优缺点(如果有)?
答案 0 :(得分:2)
更好的是DI:^)
include ("myclass.php");
function x (\MyClass $theClass) {
$theClass->theProperty="foo";
$theClass->doStuff ();
}
function y (\MyClass $theClass) {
$theClass->theProperty="bar";
$theClass->doStuff ();
}
但这取决于......:^)