有人编写了以下php4代码,我现在正尝试移植到php5:
这个类是Foo(名称改为保护有罪)。 在其中一个方法中,我们称之为save(),这个类显然是这样重置的:
$this = new Foo($this->Foo_Id);
导致以下错误:
( ! ) Fatal error: Cannot re-assign $this in ...
我的想法是像这样修复它,但我担心它可能不一样:
$this->Foo($this->Foo_Id);
当我包含该类时,PHP不再抛出解析/致命错误,但就像我说的那样,我是否会实现与php4构造相同的东西?
答案 0 :(得分:2)
在不知道组织类的上下文的情况下,很难告诉您正确的解决方案。
根据这一点,你可以做一个:
return new Foo($this->Foo_Id);
调用“save”方法的代码将获得Foo的实例。从外面看,这可能是:
befor:
$instance->save($ID);
$instance->methodFromClassFoo(); # Instance would be now of class foo. (which btw. is really bad design.
后:
$foo = $instance->save($ID);
$foo->methodFromClassFoo();
甚至:
$instance = $instance->save($ID); // Instance is now instance of foo.
$instance->methodFromClassFoo();
也许这会对你有所帮助。
答案 1 :(得分:1)
不,它不会。这将只重新运行构造函数中的任何实际代码(顺便说一句,你可能应该重命名为__construct()
),而不会影响任何实际没有设置的属性。