0

これはばかげた質問ですが、知りたいのですが、オブジェクトに値を与え、オブジェクトを失わないようにするOOP機能の名前は、たとえばjavascriptではStringオブジェクトで機能しますが、作成したい場合は値を設定できるオブジェクト、それをどのように行うのですか?:

// i set beer to budweiser
beer = new String('budweiser');

// beer is still String object and i changed its value ..
beer = 'Pabst';

しかし、PHPでは次のようなことをします:

//robert is a new guy instance, and he is cool
$robert = new Guy('cool');

//but you discover he is stealing ur money
$robert = 'asshole';

//now if i want to use a Guy method, i cant
$robert->throwRocks();

だから私は知りたいのですが、このOOP機能はどのように命名され、PHPとJSでどのように使用できますか?

ありがとう !

4

1 に答える 1

0

私はあなたの質問(またはユーモア)を理解しているのかわかりませんが、クラスを作成し、construct&を介してそのクラスに変数を割り当て__set、メソッドまたはプロパティを介してそれらを取得できます。

ここにいくつかの擬似コードがあります:

<?php 
Class guy{
    private $vars = array();

    //Assigns name from the passed param
    function __construct($name){
        $this->name = $name;
    }

    public function __set($index, $value){$this->vars[$index] = $value;}
    public function __get($index){return $this->vars[$index];}

    public function getName(){
    return $this->name;
    }
}

$guy = new guy('Bob');

echo $guy->getName(); //Bob

$guy->name = "Steve";

echo $guy->getName(); //Steve

$guy->somerandVar = 'Bill'; //(Can only set because of the __set setter)

echo $guy->somerandVar; //Bill //Can only get because of the __get getter
?>
于 2012-04-19T06:02:58.843 に答える