Skip to content

Instantly share code, notes, and snippets.

@AmyStephen
Last active Dec 25, 2015
Embed
What would you like to do?
<?php
/**
* Cat Class
*
* @package Test
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @copyright 2013 Amy Stephen. All rights reserved.
*/
namespace Animal;
/**
* Cat Class
*
* @author Amy Stephen
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @copyright 2013 Amy Stephen. All rights reserved.
* @since 1.0
*/
class Cat
{
/**
* Make the Cat Speak
*
* @return $this
* @since 1.0
*/
public function speak()
{
echo 'Meow!';
return $this;
}
}
<?php
/**
* Dog Class
*
* @package Test
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @copyright 2013 Amy Stephen. All rights reserved.
*/
namespace Animal;
/**
* Dog Class
*
* @author Amy Stephen
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @copyright 2013 Amy Stephen. All rights reserved.
* @since 1.0
*/
class Dog
{
/**
* Make the Dog Speak
*
* @return $this
* @since 1.0
*/
public function speak()
{
echo 'Woof!';
return $this;
}
}
<?php
/**
* SPL-Autoload test
*/
$test_map = array(
'Animal\\Dog' => __DIR__ . '/Dog.php',
'\\Animal\\Cat' => __DIR__ . '/Cat.php',
);
spl_autoload_register(
function ($class) use ($test_map) {
echo 'PHP Sent in thus: <pre>';
var_dump($class);
echo '</pre>';
if (array_key_exists($class, $test_map)) {
require_once $test_map[$class];
}
}
);
/**
* Instantiate using Qualified Namespace
*/
echo 'Class constructed using a Qualified Namespace.<br />';
echo 'PHP will request Animal\Dog, not \Animal\Dog';
echo 'spl_autoload will work fine since Animal\\Dog is stored in the map';
$dogClass = '\\Animal\\Dog';
$dog = new $dogClass();
$dog->speak();
/**
* Instantiate using an Unqualified Namespace
*/
echo 'Class constructed using an Unqualified Namespace.<br />';
echo 'PHP will request Animal\Cat';
echo 'spl_autoload will not locate a matching classmap entry since it stored \\Animal\\Cat';
$catClass = 'Animal\\Cat';
$cat = new $catClass();
$cat->meow();
/**
* Instantiate using a Fully Qualified Namespace
*/
echo 'PHP will never send a FQCN to spl_autoloader. It strips the leading namespace separator.';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment