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

Im not sure I understand your question (nor the humour), but you can make a class and assign variables to that class through the construct & __set then retrieve them through a method or property:

Here is some pseudo code:

<?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 回答