0

我正在拼命学习如何在 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();

我想避免在那里使用“全球”,因为我被告知这是邪恶的。

而且我不想像 showLogin($user) 一样将 $user 传递给 showLogin()。在这个非常简单的情况下,这是有道理的,但是当我在执行非常复杂的函数时,这些函数会在许多这样的数组上绘制,我不想让每个数组都通过。

4

2 回答 2

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;
}

}

于 2013-09-23T13:26:51.043 回答
0

首先你需要有一个类的实例$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
于 2013-09-23T13:30:59.427 回答