繁体   English   中英

如何在PHP类中声明全局变量

[英]How do declare global variable in PHP class

class Auth extends Controller {

    function __constructor(){
        private $pass;
    }
    function Auth()
    {
        parent::Controller();   
        $this->load->library('session');
        $this->load->helper('cookie');
        $this->load->library('email');
    }
    function index(){
            ..........
    }
    function loging(){
                $this->pass = "Hello World";
    }
    function test(){
                 var_dump($this->pass); // this is on the  line 114
    }
}

当我访问测试功能时,出现以下错误:

解析错误:语法错误,第6行的/var/www/clients/client1/web15/web/application/controllers/auth.php中出现意外的T_PRIVATE

而不是字符串“ Hello World”。 我想知道为什么 ? 谁能帮我这个 ? 提前Thx

首先,您不是要创建“全局变量”(如您的标题所示),而是创建一个私有成员变量。

为此,您需要在构造函数外部声明私有成员变量:

class Auth extends Controller {

    private $pass;

    function __construct(){
    }

    function auth()
    {
        parent::Controller();   
        $this->load->library('session');
        $this->load->helper('cookie');
        $this->load->library('email');
    }
    function index(){
            ..........
    }
    function loging(){
        $this->pass = "Hello World";
    }
    function test(){
        echo $this->pass;
    }
}

也:

  • 更正您的构造函数的名称
  • 选择命名约定(例如,函数名的小写第一个字符)并坚持使用。

作为简单的答案/您要问的例子。 尝试这个:

<?php

    class Auth {

        private $pass;

        function __construct(){
        }

        function loging(){
            $this->pass = "Hello World";
        }
        function test(){
            echo $this->pass;
        }
    }

    $oAuth = new Auth();
    $oAuth->loging();
    $oAuth->test();

?>

它输出:

C:\>php test.php
Hello World

像这样 :

class Example extends CI_Controller
{

  public $variable = "I am Global";

  public function test()
  {
    echo $this->variable; // I am Global
  }

  public function demo()
  {
    echo $this->variable; // I am Global
  }

}

或者在您的情况下,将变量$pass public而不是private

public $pass;//<==make change here 

并使用$this使用变量

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM