【问题标题】:PHP Passing global variables within functions in a classPHP在类中的函数内传递全局变量
【发布时间】:2015-03-26 15:21:05
【问题描述】:

我想要输出“你好”,但没有得到任何结果。结果页面为空。这段代码中的错误是什么?这段代码只是一个模板。原始代码太长。不使用类时它工作正常。

class a{

    public function one() {

      global $newVar;
      $newVar = "hello";
    }

    public function two() {
        one();    
        global $newVar;
        echo $newVar;
    }
}

$ab = new a;
$ab->two();

【问题讨论】:

  • 因为它是一个类方法,你必须使用 $this 例如$this->one();
  • 检查您的错误日志或启用错误显示。
  • 你为什么还要在课堂上使用全局变量?您可能需要班级成员。
  • 你不应该使用global 声明......总有另一种方式......

标签: php function class global


【解决方案1】:

您可能在某处收到此错误:

PHP 致命错误:调用未定义的函数 one()

这是因为没有从two 调用的全局函数one。不过,有一个可以调用的类方法one

public function two() {
    $this->one();    
    global $newVar;
    echo $newVar;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-25
    • 1970-01-01
    • 2013-02-21
    • 2011-06-13
    相关资源
    最近更新 更多