Last active
December 14, 2015 16:09
-
-
Save dongilbert/5113138 to your computer and use it in GitHub Desktop.
An (potentially) improved loadClass method for the PSR-0 autoloader that eliminates naming collisions at the (potential) sake of performance. Untested.
This file contains hidden or 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 | |
public function loadClass($className) | |
{ | |
if (null === $this->_namespace || $this->_namespace.$this->_namespaceSeparator === substr($className, 0, strlen($this->_namespace.$this->_namespaceSeparator))) { | |
$fileName = ''; | |
$namespace = ''; | |
if (false !== ($lastNsPos = strripos($className, $this->_namespaceSeparator))) { | |
$namespace = substr($className, 0, $lastNsPos); | |
$className = substr($className, $lastNsPos + 1); | |
$filePath = str_replace($this->_namespaceSeparator, DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR; | |
} | |
$fileName = $filePath . $className . $this->_fileExtension; | |
include ($this->_includePath !== null ? $this->_includePath . DIRECTORY_SEPARATOR : '') . $fileName; | |
// Check if the actual class has been found, not just it's supposed containing file. | |
if (class_exists($namespace . '\\' . $className, false) { | |
return true; | |
} else { | |
// If it's not found, try to load it again, this time replacing _'s as well. | |
$fileName = $filePath . str_replace('_', DIRECTORY_SEPARATOR, $className) . $this->_fileExtension; | |
include ($this->_includePath !== null ? $this->_includePath . DIRECTORY_SEPARATOR : '') . $fileName; | |
if (class_exists($namespace . '\\' . $className, false) { | |
return true; | |
} else { | |
// STILL not found? Give up. | |
return false; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment