开发者

Method chanining and re-use of same class

I have the following class:

class DB {

    private $name;

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

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

At the moment if I do:

$db = new DB();
echo $db->load('foo')->get() . "<br>";
echo $db->load('fum')->get() . "<br>";

This outputs "foo" then "fum".

However if I do this:

$db = new开发者_JS百科 DB(); 
$foo = $db->load('foo');
$fum = $db->load('fum');
echo $foo->get() . "<br>";
echo $fum->get() . "<br>";

It always outputs "fum".

I can sort of see why it would do that, but how could I keep the variable seperate to each instance without having to create a new instance of DB?


IF you mean for DB to be some sort of database connectivity object (which I assume you are), multiple instances may not be the best choice. Perhaps something like this may be what you are trying to do:

$db = new DB(); 
$foo = $db->load('foo')->get();
$fum = $db->load('fum')->get();
echo $foo . "<br>";
echo $fum . "<br>";

If what I think you are trying to do is correct, it may be better to separate your get logic from the DB class into its own Record class.

class Record {
    function __construct($name) {
        $this->name = $name;
    }

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

    private $name;
}

class DB {

    public function load($name) {
        return new Record($name);
    }
}

$db = new DB(); 
$foo = $db->load('foo');
$fum = $db->load('fum');
echo $foo->get() . "<br>";
echo $fum->get() . "<br>";


To keep it separate to each instance, you would, by definition, need to create a new instance... You could do that though in the load() method. Instead of returning $this, you could return a new DB() configured the way you want. Then make the method static.

This is what's called the factory pattern.


What you're experiencing in your code is similar to PHP's pass by reference feature.

When you set the first variable, $foo is equal to the value of $db->name, when you call it again to set it to 'fum', you're setting $fum equal to $db->name. Since you're echoing them both at the end, they're both going to be the last value you set it to.

Try this and see if your results are different.

$db = new DB(); 

$foo = $db->load('foo');
echo $foo->get() . "<br>";

$fum = $db->load('fum');
echo $fum->get() . "<br>";

When you run $db->load(), create a new object and return that instead of the object you're currently in.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜