How to use final in PHP?

If someone would ask me about my favorite keyword in PHP, I would certainly answer: final. It doesn’t mean I write this modifier in each class or method. It not only shows the intention but also provides a mechanism to protect the code. At least from the assumption.

The final keyword can be used both on the class level and on the method level. It prevents future extension of functionalities in a non-effective way. If a class is marked as final, then we can’t inherit from it. If a method is marked as final, we can’t override it.

The theory sounds good. Let’s go to details.

Read more →

Don’t use properties and methods from outside the interface

It may sound obvious or even weird for people who programming in statically typed or compiled languages. In my work, I use PHP which is a dynamically typed language with optional strict typing introduced in version 7. At the beginning of my journey with PHP, I didn’t care so much about typing. I had a trivial cause — they didn’t exist yet.

I used to write a code without thinking about types. It was convenient and fast. Furthermore, it allowed writing proxy functions which recognize parameters type and it runs the proper function. Yes, overriding doesn’t exist in PHP.

But things changed when I discovered polymorphism. The magic keyword Interface that allows us to define the mandatory set of features in the object. The picture of writing a code without worrying about missing methods was incredible. I still didn’t understand one thing yet. How interfaces help me since I can pass everything on the function call?

This question lied a long time in my head until I discovered I can define the required type of passed object. Since that time, I changed completely the way how I write the code.

Read more →