Seun Lanlege
Seun Lanlege

Reputation: 1356

What is this php notation called?

I saw this somewhere on the Internet. Can't remember where but I tried it out and it works. It's supposed to allow for sequential execution of functions.

Chmod('file', 0777).chroot('file','root').redirect('/') ;

By adding '.' after my function calls I can immediately execute another function. I've searched the entire Internet for it but the problem is I don't know what it is called so I decided to ask here. I would like to read its full documentation.

Upvotes: 1

Views: 81

Answers (2)

Narf
Narf

Reputation: 14752

This is not a "notation", just a weird exploitation of the concatenation operator (the dot).

It basically exploits PHP's type-juggling, converting each of the function return values to a string.

chmod() and chown() will return booleans, implicitly casted to empty strings.
redirect() is a function probably provided to you by a framework, and most likely returns void (i.e. noting), which is again casted to an empty string.

It will not work with functions that return arrays, or objects that don't implement the __toString() magic method - the only value types that can't be casted to string.

The following will make more sense:

$value = Chmod('file', 0777).chroot('file','root').redirect('/') ;

... only you don't actually care about $value, which you know would be a useless empty string.

I assume you find it "nice" and given my explanation, will probably think it's also "smart", but it is technically wrong.

Replacing the dots with semi-colons would be doing it "the right way". It's just that we are used to reading dots as method chaining in other languages, and is thus easier to read them as opposed to the semi-colons.

So, don't be surprised when somebody else calls it "ugly" - you're not supposed to do it and it is technically a "hack".

Upvotes: 3

vuryss
vuryss

Reputation: 1300

You cannot do that in PHP. The dot . operator means only one thing in the language, and that is concatenation of strings.

You can do a method chaining, which is similar. That is achieved by returning $this from every not final (which means it should return actual result or make final action) method in the class.

Upvotes: 0

Related Questions