类的方法中的未定义变量

编程入门 行业动态 更新时间:2024-10-26 21:20:11
类的方法中的未定义变量 - PHP(Undefined variable in a method of a class - PHP)

我想知道为什么我的下面的代码不起作用。 它给了我这个错误:

(!)注意:未定义的变量:第8行的C:\ wamp \ www \ oops \ visibility-levels \ public.php中的uname

<?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(); ?>

但是当我将上面的代码修改为 -

<?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:

( ! ) Notice: Undefined variable: uname in C:\wamp\www\oops\visibility-levels\public.php on line 8

<?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(); ?>

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

更多推荐

本文发布于:2023-08-05 14:23:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1434051.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   未定义   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!