开发者

C++ Vs PHP - Object oriented questions:

I've been working in PHP lately and while I find the language开发者_开发技巧 pretty simple coming from C++/C#/python, etc, I have been running into some strange differences (maybe) when it comes to its OO representations. If anyone could answer a few short questions I would be very appreciative :)

  1. Can a constructor return a result value in PHP?

  2. When a member function within a class calls another member function within a class, do I have to use the self:: scoping or is that just a hint?

  3. Why is there self:: and $this-> and what's the difference?

  4. Is there any need to delete an object created with new, or will going out of scope remove it? I'm not sure if its truly dynamic, or if there's garbage collection like in C#.

I know the questions are a little simple, and I keep seeing code that uses all these things - but I haven't seen anything concrete enough and I don't have a good php book at home :) So thank you in advance for answers!


1. Can a constructor return a result value in PHP?

No. (This was possible, but the issue has been fixed - in case you see code that suggests something else.)

2. When a member function within a class calls another member function within a class, do I have to use the self:: scoping or is that just a hint?

This normally technically works, please don't do so. Inside object instances use $this to access own properties and methods.

3. Why is there self:: and $this-> and what's the difference?

It's not the full answer, but for the intro: self:: is for static function calls and member access. See PHP: self vs. $this.

4. Is there any need to delete an object created with new, or will going out of scope remove it? I'm not sure if its truly dynamic, or if there's garbage collection like in C#.

You don't need to delete objects, there is a garbage collector. When objects leave scope they are deleted (the zval's container reference count is one). Keep in mind that everything is deleted at the end of the request in PHP. Your application normally only runs for a fraction of a second, then the process's memory is cleared anyway as the script (and PHP) terminated.


  1. No, it automatically returns an instance of $this (unless an exception is thrown)
  2. Using self:: is required when accessing static members
  3. self:: is for accessing static members, $this-> is for instance members
  4. No, the object will be garbage collected when all references to it are gone
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜