Standardizing object rendering as a string


show more Standardizing object rendering as a string provides you with in-depth training on Developer. Taught by Jon Peck as part of the Object-Oriented Programming with PHP show less
please wait ...

Standardizing object rendering as a string

Instead of just asking an object to display itself, it's more convenient to assume that when echoed, an object knows to treat itself like a string. At a high level, this concept is known as polymorphism, where I can act on an object without knowing exactly what the class is. In practice, this means more common function names between classes. I am going to cover polymorphism in greater depth in a later segment. For now, let's focus on making an address display as a string by echoing. To do this, I'm going to use the magic method _toString(), which allows an object to specify how to return a string.

I am going to switch back to the demo script. Then, at the end, add the following lines: echo <h2>Address _toString. Then echo $address_2. Refresh your browser. You will see a catchable fatal error. This is because the object does not have a method defined to convert itself to a string. Open the Address class. Under the Magic _set() method, declare a new method called _toString...

Standardizing object rendering as a string
Video duration: 2m 17s 1h 57m Intermediate Updated Apr 10, 2013

Viewers:

Standardizing object rendering as a string provides you with in-depth training on Developer. Taught by Jon Peck as part of the Object-Oriented Programming with PHP

Subject:
Developer
Software:
PHP
Author:
please wait ...