Which Method To Use - Design - Typed PHP, Stronger Types for Cleaner Code

Typed PHP, Stronger Types for Cleaner Code (2014)


Which Method To Use

We’ve had a look at a number of methods and extensions which can help us to abstract away the inconsistent type handling PHP presents to us. Part of creating this abstraction is deciding on which methods and/or extensions to use.

Namespace Methods

Generally, we should avoid any method that would expose a significant amount of functions in the global scope. We don’t want to create any more clutter than there already is, and being able to use our abstraction, in addition to the standard stuff, is definitely beneficial.

We should endeavour to have all our code reside in namespaces.

Furthermore, we should implement our code in such a way that it can be used both in procedural environments and object-oriented environments. Stated differently; we should contain the business logic within functions and call those functions (so that they can be used in procedural code) from within an object-oriented framework (so that scalar types can be used like objects).

We should build our logic in functions and add those functions (as methods) to scalar type objects.

Scalar Objects / SPL Types

This means we will want to use the namespace functions we covered earlier, and that we will also want to use either the scalar objects or the SPL Types as an Object-Oriented basis for our type system.

I mentioned that the Scalar Objects and SPL Types extensions shouldn’t be used together. That’s because they do the same thing. It’s not possible to proxy function calls (in the way I’ve just described) without repeating the whole Object-Oriented side of things for each extension.

This is due to the fact that the Scalar Objects extension automatically boxes variables while the SPL Types extension expects developers to box their own variables. It’s the different between return new static(substr($this, $offset, $length)); and return substr($this, $offset, $length);

While I love the Scalar Objects extension, I am inclined to suggest with the SPL Types extension. The main reason is that it doesn’t interfere with how PHP handles scalar types. This means we will need to box variables, but we’ll also enjoy the benefits of state (object-like scalar variables) and automatic unboxing.


As cool as Zephir is, it’s not PHP. That means any developers you want to work on your code, will need to know or learn another language. It also increases the time between coding, testing and shipping.

So, for the remainder of the book, I will show code that is built on top of SPL Types and not translated into Zephir extensions.

The appendices [will] include a PHP and a Zephir implementation. I don’t want the implementation to be a focus of the book, but I will enjoy making it!