Domanda

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
    }
}

When I access the test function I get this error:

Parse error: syntax error, unexpected T_PRIVATE in /var/www/clients/client1/web15/web/application/controllers/auth.php on line 6

instead of the string "Hello World". I wonder why ? Can anyone help me with this ? Thx in advance

È stato utile?

Soluzione

First up, you're not trying to create a "global variable" (as your title suggests), but a private member variable.

In order to do that you need to declare the private member variable outside of the constructor:

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;
    }
}

Also:

  • Correct the name of your constructor
  • Chose a naming convention (e.g. lowercase first character of function names) and stick to it.

As a trivial answer / example of what you are asking. Try this:

<?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();

?>

It outputs:

C:\>php test.php
Hello World

Altri suggerimenti

Like this :

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
  }

}

Or in your case make the variable $pass public instead of private

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

And use the variable using $this

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top