dongweiben5229 2009-09-12 01:00
浏览 44
已采纳

关于PHP中OO的问题仍在继续

Yesterday I had a few question about OO and classes in PHP here but I have a couple new questions.

1a)
In the example snippet below you will see the 3 variables set at the top of the class and then used in a method in the class. Notice how the 3 variable declared in the beginning are not set to anything, so is it required to set/list all variables a class will use at the top like that?

1b)OR are they just called at the top to set them to be protected/private/public?

1c) Is it always required to set a variable like that, let's say all the vars are public, would you still need to set them at the beginning?

<?PHP
class widget{
    private $name;
    public $price;
    private $id;

    public function __construct($name, $price){
        $this->name = $name;
        $this->price = floatval($price);
        $this->id = uniqid();
    }
}
?>
  • 写回答

2条回答 默认 最新

  • doutang6600 2009-09-12 01:04
    关注

    Variables declared within a class declaration but not within a method are "member variables" of that class - they're scoped to the class only but are available to all methods of that object, and a new set of each will be created for each instance of the object.

    $a = new widget("first", 0.1);
    $b = new widget("second", 0.2);
    
    echo $a->price; // will echo 0.1
    echo $b->price; // will echo 0.2
    echo $price; // will not echo anything unless you set $name to something elsewhere
    
    echo $name; // will not echo anything unless you set $name to something elsewhere
    echo $a->name; // will give you an error since 'name' is private to the class
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?