Created
March 7, 2016 04:12
-
-
Save luckily/7ec8ad29aafe3691848c to your computer and use it in GitHub Desktop.
練習autoload
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace MyNamespace\Alice; | |
class Dog | |
{ | |
public function bark() | |
{ | |
return '汪汪'; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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