开发者

PHP this pseudo variable

From the PHP manual:

class Bear {
// define properties
public $name;
public $weight;
public $age;
public $sex;
public $colour;

// constructor
public function __construct() {
    $this->age = 0;
    $this->weight = 100;
}

I'm interested in what would happen in terms of ob开发者_Python百科jects and classes if the line: $this->age = 0; was changed to $age = 0; what exact effect does this change have?


You will assign 0 to local variable age. Since it doesn't exist, it will be initialized. Once the constructor goes out of scope, age will be forgotten. The class member age will not be changed.


The class variable "age" would be unaffected by the change. Here's a good example as to why this is the case:

class Bear {
    // define properties
    public $name;
    public $weight;
    public $age;
    public $sex;
    public $colour;

    // constructor
    public function __construct($age) {
        $age = $age * 2; // Convert to bear years.
        $this->age = $age;
        $this->weight = 100;
    }
}

Now when we create the bear, we have the option to set the age via the constructor:

$ben = new Bear(8);

We can also modify the bear's age in much the same way as we did within the constructor:

$ben->age = 12;

This gives the variable a scope. Ben's age is specific to him. It's a local variable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜