2

Someone wrote the following php4 code which I now am trying to port to php5:

the class is Foo (name changed to protect the guilty). In one of the methods, we'll call it save() the class apparently is reset like this:

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

That results in the following error:

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

My idea would be to fix it like this, but I am concerned that it might not be the same:

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

PHP doesn't throw the parse/fatal error anymore when I include the class, but like I said, am I going to achieve the same thing as the php4 construct?

Charles
  • 50,943
  • 13
  • 104
  • 142
Maarten
  • 4,643
  • 7
  • 37
  • 51

2 Answers2

2

Without knowing the context in which the classes are organized its hard to tell you the right solution.

Depending on that, you could just do a:

return new Foo($this->Foo_Id);

The code which is calling the "save" method will get an instance of Foo. From the outside this could look like:

befor:

$instance->save($ID);
$instance->methodFromClassFoo(); # Instance would be now of class foo. (which btw. is really bad design.

after:

$foo = $instance->save($ID);
$foo->methodFromClassFoo();

or even:

$instance = $instance->save($ID); // Instance is now instance of foo.
$instance->methodFromClassFoo();

maybe this helps you.

Rufinus
  • 29,200
  • 6
  • 68
  • 84
1

No, it won't. That will just rerun any actual code in the constructor (which incidentally you should probably be renaming to __construct() anyway) without affecting any properties that aren't actually set there.

chaos
  • 122,029
  • 33
  • 303
  • 309