Quantcast
Viewing latest article 10
Browse Latest Browse All 11

PHP namespaces and __autoload() for dummies (like me)

Using autoload and namespaces in PHP is for object-oriented programming.

Autoload

When building your classes and including them on pages that will use them, it can become tedious to have to write includes on every page just to use the class. Autoload is intended to make this easier by calling the __autoload() function whenever a class is instantiated.

<?php
// this function should be included in your common PHP file that's included on every page
function __autoload($className) { 
      if (file_exists(dirname(__FILE__) . '/' . $className . '.class.php')) { 
          require_once(dirname(__FILE__) . '/' . $className . '.class.php'); 
          return true; 
      } 
      return false; 
} 
?>
<?php
include('common.php');

// notice we do not need to include the class file

$myExample = new Example();
?>

Namespaces

Namespaces are intended to help organize and more importantly avoid name conflicts between classes. When used with __autoload() you get a cleaner PHP file that’s easier to read.

<?php namespace News;
class Article {
    public function getTitle() {
         return $title;
     }
}
?>
<?php include('common.php');
    use News\Article;
    $article = new Article();
    $title = $article->getTitle();
?>

Viewing latest article 10
Browse Latest Browse All 11

Trending Articles