PHP在类/对象中使用全局变量

Tom*_*mas 1 php variables class object

可能重复:
未解析基本语法的解决方法

我不明白如何在php中使用对象内部的变量.

例如在javascript中我会这样做,它会没事的.

var foo = 10,
    bar = {option: foo+5}
;

console.log(bar.option);
Run Code Online (Sandbox Code Playgroud)

在PHP我做同样但它失败了

$variable = 10;

class myObject {
    var $username = $variable + 5 ;
    var $zzz = $username + 5;

}
Run Code Online (Sandbox Code Playgroud)

也可以$this在对象中使用或仅在函数中使用?

最后,如何在myObject的第二行中基于另一个内部设置变量?:)

kap*_*apa 6

正确的方法是使用构造函数 - 一个在创建对象时运行的方法.

当你定义类的属性,你只能使用固定的值(1,'xyz',array()很适合为例),而不是需要在运行时计算的表达式.

将变量传递给构造函数,不要使用全局变量.

class myObject {
    public $username;
    public $zzz;

    public function __construct($variable) {
        $this->username = $variable + 5 ;
        $this->zzz = $this->username + 5;
    }
}

$obj = new myObject(10);
echo $obj->username; //15
Run Code Online (Sandbox Code Playgroud)

在PHP中,如果您不想编写OOP代码,则不需要使用类和对象.您可以简单地创建好的旧功能.但是如果你想使用它们,试着熟悉OOP概念.


Jos*_*ser 5

Specifically, you asked how to use global variables in PHP. To do this you would use the global keyword at the time you define your variable:

$variable = 10;

class myObject {
    function foo () {
        global $variable;
        $username = $variable + 5 ;
        $zzz = $username + 5;
    }
}
Run Code Online (Sandbox Code Playgroud)

BUT DON'T! It's a bad idea. It violates every principle of object encapsulation to do something like this, and kills a puppy every time your code runs. Ok, maybe the puppies are safe, but it's still not a good idea.

Instead you should pass the value to the object, either through the constructor, or through an accessor method. See below:

// The following code is guaranteed not to kill any puppies
class myObject {

    private $_variable;
    private $_userName;
    private $_zzz;

    public function __construct($value) {
        $this->_variable = $value;
        $this->_userName = $this->_variable + 5;
        $this->_zzz = $this->_userName + 5;
    }

}

$variable = 10;
$obj = new myObject($variable);
Run Code Online (Sandbox Code Playgroud)