Dynamic types, part 2


In a previous lesson on dynamic types we've learned that a variable can hold a values of any type and that type may change during the runtime.

There is even more. Array keys should be a string either an integer. However values of the same array can hold anything: strings, booleans, integers, floats, functions, resources, or another (nested) arrays. This is a totally fine PHP array:

$wow_array =
    4 => 'This is a string',
    'cat' => [25 => false, 0 => function() use(&$a) { return 10; }],
    17 => [true, 42.347, [], 'four', [true, fopen('text.txt', 'r')]],
    'dog' =>
        'plus' => function($a, $b)
            return $a + $b;
        7485 => null,
        'yohoho' => socket_create(AF_UNIX, SOCK_STREAM, 0)

Look at this line of code:

$foo(10, 'Todd');

Is this a valid line of code? It is, if $foo is a function. But is it a function? We don't know! We will find this out when the control flow reach this line, and not earlier.

You could get a type of a variable with gettype function. However you should use it for a debug purpose only. Using it as a part of a program logic is a bad software design (except absolutely rare cases).

$a = [1, 2, 3];
echo gettype($a); # Prints "array"
Rate this post:
Lesson 11
Share this page:

Learning plan

It's time to create your own PHP functions
How reference the same PHP values with different names
Most common and useful PHP built-in functions
10. Dynamic types, part 2
The next portion of things you should learn about PHP types
The second part of basics of PHP arrays
Things you should know to configure error reporting properly
How to split PHP script into pieces and include them into each other