Question

In languages like Ruby/Javascript, you can apply object operators to anything. I.e.,

var string = "Pancakes";
alert(string.length);
// 8

What is this called when everything is in object? Is there anything that can make PHP behave this way instead of having to hack something together yourself? Is this something that is currently requested in the PHP community?

The ability to do echo (new String("Hello"))->length() would be nice, or even "Hello"->length(); I would even settle for:

$var = "Hello";
echo $var->length;
Was it helpful?

Solution

It's called Object-oriented programming. PHP supports OOP, but a lot of the language is implemented as flat functions which accept arguments.

You would need to define your own objects if you wanted to operate on them, otherwise you're stuck with having to use functions like strlen() on the built in types such as String.

OTHER TIPS

Java programmers use the term autoboxing for the ability of calling methods on primitive values. JavaScript has this feature too, and it works by creating temporary wrapper objects. I don't know about Ruby.

In PHP that's not possible. new String("Hello")->length() is also not possible, mainly because there is no String class with methods like length. You could create your own, but is it worth it? Also, you might be interested in this hack.

They call this object oriented programming. The newer versions of PHP are OO. You can create classes with methods to accomplish what you are referring to.

Object orientation (OO) is something that was tacked on to PHP "after the fact". Before OO was implemented everything was done using functions (like many other C-like programming languages).

When it comes to PHP, strings, integers, booleans, etc. are just data. They are primitive types and cannot do anything; they are just named values stored in memory. This is why you need to use functions, like strlen($str). The function operates on the value.

In languages like Ruby and Javascript most data types, such as strings, are, practically speaking, actually objects (or in some cases kinda-sorta objects). They contain various properties like .length, and methods like .indexOf(). Another word for such data types is a composite type (they are composed of more than one thing).

So, in PHP you can say that it is normal to write strlen($str) to figure out how long a string is; likewise, in Javascript or Ruby it is normal to write str.length.

It is possible to write a String class in PHP, but it is kind of beside the point. It is like learning to count to ten, but insisting that it be done in base-7. It is not very practical, and people will think you are crazy.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top