Library Database

Basic type checking

Both Python and PHP are dynamically typed languages. That means you don’t have to declare the data types your variables will store. This loosey goosey approach lends itself to flexibility, but it also means you may have to do extra work to check that a variable contains the type of data you’re expecting. We’ll look at more advanced topics like argument, property and return hinting in another article. For now, let’s look at the basic toolkit for checking type.

PHP Code Example:

Let’s use PHP’s all-purpose gettype() function to confirm the type of an integer. We’ll also use get_class() to confirm an object’s class, and the instanceof operator to confirm that an object belongs to a particular class type.

class Person {
}

class Teacher extends Person {
}

$num = 4;
$bob = new Teacher();

print gettype($num);            // integer
print get_class($bob);          // Teacher
print $bob instanceof Teacher;  // 1

Python Code Example:

Here we reveal type() and isinstance(), These Python functions are broadly equivalent to PHP’s gettype() and instanceof.

class Person:
    pass

class Teacher(Person):
    pass

num = 4
bob = Teacher()

print(type(num))               # <class 'int'>
print(type(bob))               # <class '__main__.Teacher'>
print(isinstance(bob, Person)) # True

Discussion

PHP provides many individual type checking methods – our friends is_int(), is_string(), etc – but they all live in the shadow of the mighty gettype() which returns a string representing the type of the given variable. Python, has its own specific checkers but it, too, provides one checker to rule them all. In fact type() is arguably more flexible than PHP’s gettype().

In this example, Python’s type() performs a triple duty. First of all, it tells us that the variable num contains an integer, secondly it tells us that bob is a Teacher (whereas we need to use the specialised get_class() function in PHP), finally type() reveals an important fact about types in Python. That is, that everything is an object – an integer just as much as a Teacher or a Person.

If we attempt to use PHP’s gettype() on an object we’ll only learn that it belongs to the type object.

print gettype($bob); // object

As you can see, PHP’s instanceof operator and Python’s isinstance() function do the same job, both confirming that $bob (or bob) is, in fact, a Person.

See future articles for more on type checking.

See also

Further Reading:


Stay up to date with the Python for PHP Programmers project


Yes! Please sign me up to this newsletter


Photo by Jan Antonin Kolar on Unsplash