Skip to content

Instantly share code, notes, and snippets.

@k-holy
Created January 26, 2012 02:54
Show Gist options
  • Save k-holy/1680669 to your computer and use it in GitHub Desktop.
Save k-holy/1680669 to your computer and use it in GitHub Desktop.
include_path前提のnamespace対応autoload実装(namespaceとpearの併設エラー検証)
<?php
return 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;
};
<?php
namespace Acme;
set_include_path(implode(PATH_SEPARATOR, array(
'/path/to/vendor',
get_include_path(),
)));
spl_autoload_register(
include __DIR__ . DIRECTORY_SEPARATOR . 'autoload.function.php', true, true
);
$ns = new Klass();
var_dump(get_class($ns)); // string(10) "Acme\Klass"
$ns = new \Acme\Klass();
var_dump(get_class($ns)); // string(10) "Acme\Klass"
<?php
namespace Acme;
set_include_path(implode(PATH_SEPARATOR, array(
'/path/to/pear',
'/path/to/vendor',
get_include_path(),
)));
spl_autoload_register(
include __DIR__ . DIRECTORY_SEPARATOR . 'autoload.function.php', true, true
);
$pear = new \PEAR_Exception('GRRRR');
var_dump(get_class($pear)); // string(14) "PEAR_Exception"
$ns = new Klass();
// include_pathがpear;vendorの順だと、"Class 'Acme\Klass' not found in /path/to/autoload.php" (\Acme\Klassのロードでpearディレクトリから読み込もうとする)
var_dump(get_class($ns)); // string(10) "Acme\Klass"
$ns = new \Acme\Klass();
var_dump(get_class($ns)); // string(10) "Acme\Klass"
$pear = new \Acme_Klass();
// include_pathがvendor;pearの順だと、"Cannot redeclare class Acme\Klass in /path/to/vendor/Acme/Klass.php" (\Acme_Klassのロードでvendorディレクトリから読み込もうとする)
var_dump(get_class($pear)); // string(10) "Acme_Klass"
<?php
set_include_path(implode(PATH_SEPARATOR, array(
'/path/to/pear',
get_include_path(),
)));
spl_autoload_register(
include __DIR__ . DIRECTORY_SEPARATOR . 'autoload.function.php', true, true
);
$pear = new PEAR_Exception('GRRRR');
var_dump(get_class($pear)); // string(14) "PEAR_Exception"
$pear = new Acme_Klass();
var_dump(get_class($pear)); // string(10) "Acme_Klass"
@k-holy
Copy link
Author

k-holy commented Jan 26, 2012

return function(){};されたファイルをinclude、サンプル提示に便利(゚∀゚)

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