代码之家  ›  专栏  ›  技术社区  ›  Maarten

关于如何重置类的php 4-5移植问题

  •  2
  • Maarten  · 技术社区  · 17 年前

    有人编写了以下php4代码,我现在正试图将其移植到php5:

    这个类是foo(为了保护罪犯而更改了名称)。 在其中一个方法中,我们将其称为save()类显然是这样重置的:

    $this = new Foo($this->Foo_Id);
    

    导致以下错误:

    ( ! ) Fatal error: Cannot re-assign $this in ...
    

    我的想法是这样修复它,但我担心它可能不一样:

    $this->Foo($this->Foo_Id);
    

    当我包含这个类时,php不再抛出parse/致命错误,但是就像我说的,我是否要实现与php4构造相同的功能?

    2 回复  |  直到 13 年前
        1
  •  2
  •   Rufinus    17 年前

    如果不知道类的组织环境,很难告诉您正确的解决方案。

    根据这一点,你可以做一个:

    return new Foo($this->Foo_Id);
    

    调用“save”方法的代码将获得一个foo实例。从外部看,这可能是:

    之前:

    $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();
    

    也许这对你有帮助。

        2
  •  1
  •   chaos    17 年前

    不,不会的。这只会重新运行构造函数中的任何实际代码(顺便说一下,您可能应该将其重命名为 __construct() 无论如何)不会影响任何实际上没有设置的属性。