Static and Instance Method Calls.
PHP does not differentiate between methods called on instantiated classes and un-instantiated classes like Ruby does.
Take the following code for example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Calling these will get the following result:
1 2 3 4
In Ruby, using this code is completely legal. Ruby knows that class methods and instance methods are separate and namespaces them accordingly. This allows class and instance methods to have the same name (provided we put self. in front of a class definition or extend self within the object).
Similar code can be expressed like this in PHP:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Above we use the similar PHP concept of a static method (similar to class methods in that they can be called on non instantiated classes) and an instance method. Like the above Ruby code we gave them the same name.
One would expect that PHP would function similar to Ruby in that it will keep it’s static references separate.
However, this will cause PHP to throw a fatal error:
This is because of backward compatibility reasons. PHP 5 allows instance methods to be called on an a non-instantiated class. This can be a bit frustrating if you are coming from Ruby as the ‘::’ operator acts slightly different.
For example: If you wish to create a class called File. Perhaps you would like two similar methods that check if a file is writable. One you can pass a file name to, and the other that when called on an instantiated File object won’t need a file name – it will just reference the current object.
There are other ways to get PHP objects to act like Ruby objects and call static/instance methods separately using Object Overloading, but this is a hack and should be avoided. The rule of thumb in PHP is just to treat every method as an instance method. If you are dead set on using both static and instance methods in your PHP code, just pay extra mind to the following:
- Instance methods can be called statically: Check for the existence of $this.
- Instance methods and static methods can’t have the same name.
- __call() and __callStatic() are your best friends.
Edit: What I had here before was not technically correct. Ruby actually does not have static methods. Ruby has Class Methods. These can be referenced in a ‘static’ manner (that is, on a class rather than an object). In order to keep the post to the point, I unintentionally over simplified the differences between the two languages’ design patterns.
I’ve updated the language a bit to make the difference obvious.