I used to write a very strong type language, for example, java. I need to tell the complier what type of variable I will put in… for example…
public static void sayHello(String aName)
I can ensure that the user will pass a string to me…
But if I use php, I can do that…
function sayHello($aName)
I still can call the sayHello, but I don’t know what the param type……I can let the name more informative like this:
function sayHelloWithString($aName)
But I can’t stop the user pass in a int to me….. the user can still pass the int to me… …it may cause lot of errors….How can I stop it? any ideas or experience shared? Thank you.
There’s a few ways to deal with this…
arrayand a class name.1 – To implement #1 using a good IDE, you can docblock your function as such:
2 – To implement #2 use the
is_methods..3 – You can’t do this with your method above, but something like this.. Kindof the same as #2 apart from will throw a catchable fatal error rather than
ArgumentException.It’s worth noting that most of this is pretty irrelevant unless you’re writing publicly usable library code.. You should know what your methods accept, and if you’re trying to write good quality code in the first place, you should be checking this before hand.
Using a good IDE (I recommend phpStorm a thousand times over) you can and should utilise DocBlocks everywhere you can for all of your classes. Not only will it help when writing APIs and normal code, but you can use it to document your code, what if you need to look at the code 6 months later, chances are you’re not going to remember it 100% 🙂
Additionally, there’s a lot more you can do with docblocks than just define parameter types, look it up.