2016-12-24 2 views
-2

Я хочу объявить глобальную переменную в __construct() и получить доступ к ней из другой публичной функции.Получить доступ к глобальной переменной из конструкции php

class NewMineClass(){ 
    public function __construct(){ 
    global $goaway; 
    } 

    public function imHere(){ 
    $this->goaway; 
    } 
} 

Но это не работает.

+1

Возможный дубликат [ Глобальная переменная внутри конструктора с PHP] (http://stackoverflow.com/questions/1927881/g lobal-variable-inside-a-constructor-with-php) –

+0

'$ this' относится к объектным переменным. Если вы должны сделать это безумное дерьмо, а '$ goaway' было объявлено в глобальной области, то используйте' $ GLOBALS'. Покажите больше кода, например, где '$ goaway' исходит из лучших результатов. – AbraCadaver

+0

имя класса должно быть без() – denny

ответ

2

Встреча class properties. Я думаю, что лучше всего объяснить на примере:

// Note that the class name needs no parenthesis 
class NewMineClass 
{ 
    // This is a class property, it's accessible within the class scope. 
    // All the methods of this class can access it using `$this->goaway`. 
    // If you want it to be accessible from outside the class, you need 
    // to declare it as public instead of protected. 
    protected $goaway; 

    public function __construct() 
    { 
     $this->goaway = 'something i want to initialize in the constructor'; 
    } 

    public function imHere() 
    { 
     echo $this->goaway; 
     // Prints: something i want to initialize in the constructor 
    } 
} 

я призываю вас читать о понятиях PHP ООП:

Смежные вопросы