开发者

Overloading in PHP?

Can someone please explain how overloading 开发者_运维问答in PHP works? The manual doesn't do a very good job of it. I'm still thinking of overlaoding in the Java sense, but I know overloading in PHP is a completely different animal. All the PHP manual says is that overloading provides a mechanism for adding new properties and methods to a class at runtime, but it doesn't explain how PHP achieves this. Thanks in advance. Rylie


All the PHP manual says is that overloading provides a mechanism for adding new properties and methods to a class at runtime, but it doesn't explain how PHP achieves this.

The very manual page you linked to explains how the thing that PHP calls "overloading" works. You're pretty correct in that it has little to do with what the entire rest of the world calls overloading. In fact, the manual page says right at the top:

PHP's interpretation of "overloading" is different than most object oriented languages. Overloading traditionally provides the ability to have multiple methods with the same name but different quantities and types of arguments.

PHP has reserved a handful of special method names that you can optionally define in a class. They fall into two categories:

  1. __get, __set, __isset and __unset are called when an instance variable (object property) is fetched, set, checked for existence, or unset respectively. All receive the name of the property as the first argument, and __set receives the new value as the second argument. These methods are only called when either the property does not exist or can not be accessed from the caller's scope (i.e. protected/private). It's worth noting that without these methods, PHP will silently create new instance variables on demand, when asked to.
  2. __call and __callStatic are called when a method is called that, again, doesn't exist or can't be accessed from the caller's scope. The former is called for instance methods, the latter for class methods. The first argument is the name of the method called, and the second is an array of the arguments, by value (references are dereferenced).

These functions allow you to simulate adding methods to a class/instance after creation, though their use is clunky and awkward. Further, using them breaks autocomplete in IDEs.

Using anonymous functions might seem like a natural complement to this functionality, but it is currently not possible to bind an the instance ($this) to one at run time. This functionality was removed during the 5.3 beta because it couldn't be made clear and obvious. This has been corrected in PHP's current trunk, but it's unknown when the trunk will be stabilized for release.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜