Skip to content

Instantly share code, notes, and snippets.

@k-holy
Created January 25, 2012 10:19
Show Gist options
  • Save k-holy/1675742 to your computer and use it in GitHub Desktop.
Save k-holy/1675742 to your computer and use it in GitHub Desktop.
include_path前提のnamespace対応autoload実装
<?php
namespace Acme;
set_include_path(implode(PATH_SEPARATOR, array(
'/path/to/pear',
'/path/to/vendor',
get_include_path(),
)));
spl_autoload_register(function($className) {
$className = ltrim($className, '\\');
if (false !== ($pos = strrpos($className, '\\'))) {
$namespace = substr($className, 0, $pos);
$className = substr($className, $pos + 1);
$fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace)
. DIRECTORY_SEPARATOR
. str_replace('_', DIRECTORY_SEPARATOR, $className);
} else {
$fileName = str_replace('_', DIRECTORY_SEPARATOR, $className);
}
if (false !== ($path = stream_resolve_include_path($fileName . '.php'))) {
return include $path;
}
return false;
}, true, true);
$e = new \PEAR_Exception('GRRRR');
$k1 = new \Acme\Klass();
$k2 = new Klass();
var_dump(get_class($e));// string(14) "PEAR_Exception"
var_dump(get_class($k1));// string(10) "Acme\Klass"
var_dump(get_class($k2));// string(10) "Acme\Klass"
@k-holy
Copy link
Author

k-holy commented Jan 25, 2012

https://gist.github.com/1318652 の続き
https://gist.github.com/1127033 が元ネタ

include_path前提のため、
/vendor/Hoge/src/Hoge/
/vendor/Hoge/tests/
といったディレクトリ構成の場合は使えませんが、ユニットテストの初期化スクリプトには便利かも

@k-holy
Copy link
Author

k-holy commented Jan 26, 2012

名前空間のクラスとPEAR形式のクラスが併設されている時に発生するエラーの検証コードはこっち
https://gist.github.com/1680669

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment