0
votes

I have recently been appointed as a Developer in a project which uses PHP backend. With previous experience in strongly typed languages like C#, it has been tough for me. In C#, it easier to:-

  • Find all references
  • Better debug experience
  • Know what type of object to be expected

and many more...

I know the benefits of a weakly typed language like JavaScript which opens the possibility of a whole lot of things you can do with it. But when you have business logic with business objects, I would rather prefer a strongly typed language.

My real question is if you have something like this:-

public function saveEntity($externalId, $layer, $sign = null, $user= null, $pass = null) {

How am I supposed to know what $layer contains without having to read all of the lines of code before a call to this function? Is there a trick/gotcha in places like these where identifying the type of object is important?

1
I hope they added comments. - Salman A
Use phpdocs to help knowing the type and content of each parameter - Elias Soares
Also you can use a good ide like phpstorm to follow references and function usages (ctrl+click or ctrl+b I think) - Elias Soares

1 Answers

4
votes

Two approaches.

You can use phpdoc to annotate your methods and variables:

/**
 * @param int $externalID
 * @param Layer $layer
 * ...
 * @return boolean
 */
public function saveEntity($externalId, $layer, $sign = null, 
                           $user= null, $pass = null) { ... }

Or just write the type in the method declaration (requires PHP >= 7):

public function saveEntity(int $externalId, Layer $layer, $sign = null, 
                           $user= null, $pass = null): boolean { ... }

Or, preferably, use both.

Doing this consistently in your code gives you all you need while still reaping the benefits of a dynamic language. Your IDE can then do refactoring, find usages and issue warnings etc.