我想知道为什么我的下面的代码不起作用。 它给了我这个错误:
<?php class User { public $uname = "admin"; public function setUsername() { $this->uname = $uname; } public function getUsername() { return $this->uname; } } $user = new User(); $user->setUsername(); echo $user->getUsername(); ?>(!)注意:未定义的变量:第8行的C:\ wamp \ www \ oops \ visibility-levels \ public.php中的uname
但是当我将上面的代码修改为 -
<?php class User { public $uname; public function setUsername($uname) { $this->uname = $uname; } public function getUsername() { return $this->uname; } } $user = new User(); $user->setUsername("admin"); echo $user->getUsername(); ?>然后它工作正常,并给我以下输出 -
管理
但我不明白为什么我在我的第一段代码中得到了未定义的变量uname。 任何的想法?
I would like to know why my following code doesn't work. It is giving me this error:
<?php class User { public $uname = "admin"; public function setUsername() { $this->uname = $uname; } public function getUsername() { return $this->uname; } } $user = new User(); $user->setUsername(); echo $user->getUsername(); ?>( ! ) Notice: Undefined variable: uname in C:\wamp\www\oops\visibility-levels\public.php on line 8
But when I modify my above code to -
<?php class User { public $uname; public function setUsername($uname) { $this->uname = $uname; } public function getUsername() { return $this->uname; } } $user = new User(); $user->setUsername("admin"); echo $user->getUsername(); ?>Then it works fine and gives me following output -
admin
But I dont understand why I got undefined variable uname in my first segment of code. Any idea?
最满意答案
因为函数setUserName不知道变量$ uname的值,所以需要在范围内定义它,或者通过函数参数传递。
例如:
public function setUsername() { $uname = 'foo'; $this->uname = $uname; }将导致输出:foo
because function setUserName doesn't know value of variable $uname, you need to define it inside the scope, or pass via function argument.
for example:
public function setUsername() { $uname = 'foo'; $this->uname = $uname; }will result in output: foo
更多推荐
发布评论