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

まず、クラスのインスタンスが必要です$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 に答える