6kxwjq
Last Updated: February 25, 2016
·
709
· wilk

PHP: how to test a module in Python-style

Testing a class is easy to do with Python by adding the following condition at the end of the file:

if (__name__ == '__main__'):
  # module test

This way it's possible to test the class by executing the file as a script.
This part of code won't be executed instead if the file is imported as a module.

Well, you can do the same thing with PHP by using the debug_backtrace function!

if (!debug_backtrace ()) {
  // module test
}

Following a complete example:

// Person.php
<?php
  class Person {
    private $name;
    public function __construct ($name) {
      $this->name = $name;
    }
    public function introduce () {
      echo 'Hello, my name is ' . $this->name;
    }
  }

  if (!debug_backtrace ()) {
    $wilk = new Person ('Wilk');
    $wilk->introduce ();
  }
?>

When Person.php is directly executed it will print out: 'Hello, my name is Wilk', but if we include class Person in another file, it's as follows:

// Developer.php
<?php
  class Developer extends Person {
    private $language;
    public function __construct ($name, $language) {
      $this->language = $language;
      parent::__construct ($name);
    }
    public function introduce () {
      echo $this->name ' knows ' . $this->language;
    }
  }

  if (!debug_backtrace ()) {
    $wilk = new Developer ('Wilk', 'PHP');
    $wilk->introduce ();
  }
?>

it will print out: Wilk knows PHP
instead of: Hello, my name is WilkWilk knows PHP

Now, go and write testable classes!