首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对象实例化PHP类的本地范围还是全局范围?

问对象实例化PHP类的本地范围还是全局范围?
EN

Stack Overflow用户
提问于 2014-04-10 08:58:55
回答 1查看 92关注 0票数 0

在为网站编写PHP代码时,更好的是:

代码语言:javascript
复制
<?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
  }

?>

或者:

代码语言:javascript
复制
<?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的每个范围,有哪些优点和缺点?

EN

回答 1

Stack Overflow用户

发布于 2014-04-10 09:00:46

更好的是下模 :^ )

代码语言:javascript
复制
  include ("myclass.php");

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

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

但这取决于..。*^)

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22983321

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档