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条)

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题的应用
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办