Skip to content

Instantly share code, notes, and snippets.

@luckily
Created March 7, 2016 04:12
Show Gist options
  • Save luckily/7ec8ad29aafe3691848c to your computer and use it in GitHub Desktop.
Save luckily/7ec8ad29aafe3691848c to your computer and use it in GitHub Desktop.
練習autoload
<?php
function autoload($className)
{
if(strpos($className, '\\') === false) {
$psr4Paths = [
'MyNamespace\\Alice\\',
'MyNamespace\\Joel\\',
];
foreach ($psr4Paths as $path) {
includeFile($path.$className);
}
return;
}
includeFile($className);
}
function includeFile($className)
{
$className = ltrim($className, '\\');
$fileName = str_replace('\\', DIRECTORY_SEPARATOR, $className);
$fileName .= '.php';
// echo '<br>'.$className.'<br>';
// echo '<br>'.$fileName.'<br>';
if(is_file($fileName))
include __DIR__ . '/' . $fileName;
}
spl_autoload_register('autoload');
<?php
// 目錄結構
// test-autoload
// |
// ---index.php
// |
// ---autoload.php
// |
// ---MyNamespace
// |
// -------Alice
// | |
// | -----Dog.php
// | |
// |
// -------Joel
// | |
// | -----Cat.php
// | |
require_once 'autoload.php';
use MyNamespace\Alice;
use MyNamespace\Joel;
// 可以使用
$dog = new MyNamespace\Alice\Dog();
echo $dog->bark();
$cat = new MyNamespace\Joel\Cat();
echo $cat->bark();
// // 使用use失敗
// $dog = new Dog();
// echo $dog->bark();
// $cat = new Cat();
// echo $cat->bark();
<?php
namespace MyNamespace\Alice;
class Dog
{
public function bark()
{
return '汪汪';
}
}
<?php
namespace MyNamespace\Joel;
class Cat
{
public function bark()
{
return '喵喵';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment