Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 51 / 68

Functions That Work with Any Type

In this lesson you will learn to write generic functions that take advantage of PHP being dynamically typed. This is for anyone searching for "what is PHP dynamic typing".

PHP is a dynamically typed language, so a function can generally accept a value of any type. Writing a function that does not commit to one type lets you reuse the same logic for numbers and for strings. That flexibility comes at a cost: an unintended type causes no error and can lead to a defect.

The sample code has larger($a, $b) handle both numeric and string comparison with the same logic. The > operator compares magnitude for numbers and dictionary order for strings, so one function serves both.

A common stumbling block for beginners is writing type-blind code and running into an unexpected implicit conversion. Type declarations make things much safer, and features such as strict_types let you combine dynamic flexibility with safety.

Large real-world codebases widely adopt declare(strict_types=1); to prevent implicit conversions. The design question is how to balance flexibility against safety.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)