同一类的方法链和重用
我有以下课程:
class DB {
private $name;
public function load($name) {
$this->name = $name;
return $this;
}
public function get() {
return $this->name;
}
}
目前,如果我这样做:
$db = new DB();
echo $db->load('foo')->get() . "<br>";
echo $db->load('fum')->get() . "<br>";
这将输出“foo”,然后“fum”。
但是,如果我这样做:
$db = new DB();
$foo = $db->load('foo');
$fum = $db->load('fum');
echo $foo->get() . "<br>";
echo $fum->get() . "<br>";
它总是输出“fum”。
我可以理解为什么它会这样做,但是如何将变量保持在每个实例中,而不必创建新的数据库实例?
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 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您的意思是数据库是某种数据库连接对象(我假设您是),那么多个实例可能不是最佳选择。也许这样的事情可能就是您想要做的事情:
如果我认为您想要做的事情是正确的,那么最好将您的获取逻辑从 DB 类分离到它自己的 Record 类中。
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:
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.
为了使其与每个实例分开,根据定义,您需要创建一个新实例...您可以在
load()
方法中执行此操作。您可以返回按您想要的方式配置的new DB()
,而不是返回$this
。然后将该方法设为静态。这就是所谓的工厂模式。
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 anew DB()
configured the way you want. Then make the method static.This is what's called the factory pattern.
您在代码中遇到的情况与 PHP 的传递引用功能类似。
当您设置第一个变量时,
$foo
等于$db->name
的值,当您再次调用它以将其设置为'fum'时,您将$fum
设置为$db->name
。由于您在最后对它们进行了回显,因此它们都将是您设置的最后一个值。尝试一下,看看你的结果是否不同。
当您运行
$db->load()
时,创建一个新对象并返回该对象,而不是当前所在的对象。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.
When you run
$db->load()
, create a new object and return that instead of the object you're currently in.