Thursday, September 2, 2010

A little bit more about string concatenation, echo and print in PHP

PHP as a language has many interesting features. One of them is string concatenation and special abilities of two the most popular constructs: print and echo. To do not make a lot of text I'll write them all in one example:
What we will see as result?

Let me describe some features related to this code:
  • Only print can be used as function and it alays return 1
  • Only echo allow concat strings by comma
  • Both print and echo can be used without parentheses
On the last feature I was cought up once.

So, let's imagine that we are PHP parsers and look what happens in mentioned code:
So easy features but so many nuances...

More about this topic: on altervista

Monday, August 2, 2010

Do you really know everything about private and public?

I've seen for a long time that usual questions about access modificators in OOP limited on enumeration (public, protected, private) and what can be enherited. However many developers (including PHP and C++ ) don't even think about how this modifiers influent on object instances presuming that they behave exactly the same as classes. But this is not true.

For example: We have class A. This class has private property $pr. Also this class has method that takes two arguments: Some string and another (second) instance of class A. This method will change $pr property of given (second) instance of class A. How comiler/translator will behave?

Let's try:
What this code will output? The most of people will say "Of course fatal error. $objOne tryes to change private property of another object". But in fact we should always remember that: access modifiers (including private) restrict access for another classes, not for objects (instance). Code will run and user will see "passed" because all job is doing in one class. This is OOP fundamental, that's why this behavoiur should be same in both PHP and C++ (and other OOP languages).