我拼命想学习如何在PHP中使用类。我正在尝试创建一个简单的类来复制将用户信息存储为数组的坏习惯,我将首先将其设置为“全局”,然后将其用于函数中。
下面是我非常笨拙地尝试上课。它有100个原因无效。你能解决它吗?
class user{
private $user;
function __construct(){
$user=/*some SQL to create a $user array. Assume one pair is 'firstname'=>'Brian'*/
}
function showValue($key) {
echo $user[$key];
}
function changeValue($key,$newValue) {
$user[$key]=$newValue;
}
}
echo "Hello there ".user->showValue('firstname')."!"; //should echo: Hello there Brian!
user->changeValue('firstname',"Steven");
echo "Now your name is ".user->showValue('firstname'); //should echo: Now your name is Steven
//the same class needs to work inside a function too
function showLogin() {
echo "Logged in as ".user->showValue('firstname');
}
showLogin(); //Should echo: Logged in as Steven
更新
我之所以不想再这样做是因为我经常不得不在这样的函数中使用数组:
function showLogin() {
global $user;
echo "Logged in as ".$user['firstname'];
}
showLogin();
我想避免在那里使用“全球”,因为我被告知这是邪恶的。
而且我不想将$ user传递给showLogin(),例如showLogin($ user)。在这个非常简单的情况下它是有道理的,但是当我正在执行非常复杂的函数时,这些函数可以像这样绘制很多数组,我不想让每个数组都通过。
答案 0 :(得分:1)
首先,您需要拥有类$instance = new user();
另外,为了访问班级中的成员,您需要使用$this->
您的代码应如下所示:
class user{
private $user;
function __construct(){
$this->user=/*some SQL to create a $user array. Assume one pair is 'firstname'=>'Brian'*/
}
function showValue($key) {
echo $this->user[$key];
}
function changeValue($key,$newValue) {
$this->user[$key]=$newValue;
}
}
$instance = new user();
echo "Hello there ".$instance->showValue('firstname')."!"; //should echo: Hello there Brian!
$instance->changeValue('firstname',"Steven");
echo "Now your name is ".$instance->showValue('firstname'); //should echo: Now your name is Steven
//the same class needs to work inside a function too
function showLogin() {
echo "Logged in as ".$instance->showValue('firstname');
}
showLogin(); //Should echo: Logged in as Steven
答案 1 :(得分:0)
您必须将$ user作为属性来设置值
class user{
private $user;
function __construct(){
$this->user= ....
}
function showValue($key) {
echo $this->user[$key];
}
function changeValue($key,$newValue) {
$this->user[$key]=$newValue;
}
}