I am trying to use a pre-written PHP autoloader and dreamweaver is stating that there is a syntax error. Can someone please explain what is causing the problem.
The lines which show as having syntax errors are
$autoloader = new static($dir, $ext);
spl_autoload_register([$autoloader, 'load']);
<?php
/**
* A basic PSR style autoloader
*/
class AutoLoader
{
protected $dir;
protected $ext;
public function __construct($dir, $ext = '.php')
{
$this->dir = rtrim($dir, DIRECTORY_SEPARATOR);
$this->ext = $ext;
}
public static function register($dir, $ext = '.php')
{
$autoloader = new static($dir, $ext);
spl_autoload_register([$autoloader, 'load']);
return $autoloader;
}
public function load($class)
{
$dir = $this->dir;
if ($ns = $this->get_namespace($class)) {
$dir .= DIRECTORY_SEPARATOR.str_replace('\\', DIRECTORY_SEPARATOR, $ns);
}
$inc_file = $dir.DIRECTORY_SEPARATOR.$this->get_class($class).$this->ext;
if (file_exists($inc_file)) {
require_once $inc_file;
}
}
// Borrowed from github.com/borisguery/Inflexible
protected static function get_class($value)
{
$className = trim($value, '\\');
if ($lastSeparator = strrpos($className, '\\')) {
$className = substr($className, 1 + $lastSeparator);
}
return $className;
}
// Borrowed from github.com/borisguery/Inflexible
public static function get_namespace($fqcn)
{
if ($lastSeparator = strrpos($fqcn, '\\')) {
return trim(substr($fqcn, 0, $lastSeparator + 1), '\\');
}
return '';
}
}
spl_autoload_register([$autoloader, 'load']);
This array syntax is only valid as of PHP 5.4. If DreamWeaver is using an older version of PHP syntax rules, it will complain.
Related
I'm testing PSR-4 autoloader from https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader-examples.md and something is not working.
Error:
Fatal error: Uncaught Error: Class 'Foo\Bar\Qux\Quux' not found in C:\xampp\htdocs\Home\foo-bar\index.php:11 Stack trace: #0 {main} thrown in C:\xampp\htdocs\Home\foo-bar\index.php on line 11
Line:
new \Foo\Bar\Qux\Quux;
My files:
index.php
example
loader.php
src
Qux
Quux.php
Baz.php
tests
Qux
Quux.php
BazTest.php
index.php:
<?php
require_once "Example/loader.php";
$loader = new \Example\Psr4AutoloaderClass;
$loader->register();
$loader->addNamespace('Foo\Bar', '/src');
$loader->addNamespace('Foo\Bar', '/tests');
new \Foo\Bar\Qux\Quux;
loader.php:
<?php namespace Example;
class Psr4AutoloaderClass
{
protected $prefixes = array();
public function register()
{
spl_autoload_register(array($this, 'loadClass'));
}
public function addNamespace($prefix, $base_dir, $prepend = false)
{
// normalize namespace prefix
$prefix = trim($prefix, '\\') . '\\';
// normalize the base directory with a trailing separator
$base_dir = rtrim($base_dir, DIRECTORY_SEPARATOR) . '/';
// initialize the namespace prefix array
if (isset($this->prefixes[$prefix]) === false) {
$this->prefixes[$prefix] = array();
}
// retain the base directory for the namespace prefix
if ($prepend) {
array_unshift($this->prefixes[$prefix], $base_dir);
} else {
array_push($this->prefixes[$prefix], $base_dir);
}
}
public function loadClass($class)
{
// the current namespace prefix
$prefix = $class;
while (false !== $pos = strrpos($prefix, '\\')) {
// retain the trailing namespace separator in the prefix
$prefix = substr($class, 0, $pos + 1);
// the rest is the relative class name
$relative_class = substr($class, $pos + 1);
// try to load a mapped file for the prefix and relative class
$mapped_file = $this->loadMappedFile($prefix, $relative_class);
if ($mapped_file) {
return $mapped_file;
}
$prefix = rtrim($prefix, '\\');
}
return false;
}
protected function loadMappedFile($prefix, $relative_class)
{
// are there any base directories for this namespace prefix?
if (isset($this->prefixes[$prefix]) === false) {
return false;
}
foreach ($this->prefixes[$prefix] as $base_dir) {
$file = $base_dir
. str_replace('\\', '/', $relative_class)
. '.php';
// if the mapped file exists, require it
if ($this->requireFile($file)) {
// yes, we're done
return $file;
}
}
// never found it
return false;
}
protected function requireFile($file)
{
if (file_exists($file)) {
require $file;
return true;
}
return false;
}
}
Quux.php:
<?php namespace Foo\Bar\Qux;
class Quux {
public function __construct() {
echo "Hello";
}
}
Thank you for your help.
Change this in your index.php:
$loader->addNamespace('Foo\Bar\Qux', __DIR__ . '/src/Qux');
$loader->addNamespace('Foo\Bar\Qux', __DIR__ . '/tests/Qux');
There is an error in the PSR-4-autoloader-examples.md documentation.
Unable to start project in Kohana. I have cloned it from github, than set my database info in config file and get error: Cannot redeclare class.
I have 2 methods autoload functions.
public static function auto_load($class, $directory = 'classes')
{
// Transform the class name according to PSR-0
$class = ltrim($class, '\\');
$file = '';
$namespace = '';
if ($last_namespace_position = strripos($class, '\\'))
{
$namespace = substr($class, 0, $last_namespace_position);
$class = substr($class, $last_namespace_position + 1);
$file = str_replace('\\', DIRECTORY_SEPARATOR, $namespace).DIRECTORY_SEPARATOR;
}
$file .= str_replace('_', DIRECTORY_SEPARATOR, $class);
if ($path = Kohana::find_file($directory, $file))
{
// Load the class file
require_once $path;
// Class has been found
return TRUE;
}
// Class is not in the filesystem
return FALSE;
}
/**
* Provides auto-loading support of classes that follow Kohana's old class
* naming conventions.
*
* This is included for compatibility purposes with older modules.
*
* #param string $class Class name
* #param string $directory Directory to load from
* #return boolean
*/
public static function auto_load_lowercase($class, $directory = 'classes')
{
// Transform the class name into a path
$file = str_replace('_', DIRECTORY_SEPARATOR, strtolower($class));
if ($path = Kohana::find_file($directory, $file))
{
// Load the class file
require_once $path;
// Class has been found
return TRUE;
}
// Class is not in the filesystem
return FALSE;
}
I have tried to add class_exists() before require() but it doesn't work& What I should do to start a project?
Possibly required class is included in some other file already.
I don't know how exactly you check class collision problem, but you should do something like:
function include_quietly($file) {
$conflicts = false;
$txt = file_get_contents($file);
preg_match_all("#class\s+(\w+)\s*{#muis", $txt, $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
if (class_exists($m[1])) {
$conflicts = true;
break;
}
}
if (!$conflicts)
include_once $file;
else
echo "include conflicts in file {$file}\n";
}
include_quietly($path);
I have 2 files:
1:
include_once 'Core/autoload.php';
if (!defined('NOVA_POSHTA_PATH_SDK')) {
define('NOVA_POSHTA_PATH_SDK', dirname(__FILE__) . '/');
\NovaPoshta\Core\Autoload::init();
}
autoload:
namespace NovaPoshta\Core\;
class Autoload
{
public static function init()
{
if (function_exists('__autoload')) {
spl_autoload_register('__autoload');
}
return spl_autoload_register(array('\NovaPoshta\Core\Autoload', 'load'));
}
public static function load($className)
{
$className = str_replace('NovaPoshta\\', '', $className);
$className = NOVA_POSHTA_PATH_SDK . $className . '.php';
$className = str_replace('\\', DIRECTORY_SEPARATOR, $className);
if ((file_exists($className) === false) || (is_readable($className) === false)) {
return false;
}
require($className);
return true;
}
}
If executing first code i recive this error:
Class 'NovaPoshta\Core\Autoload' not found
Help me pls. What can be is? Thanks
I'm new to PHP namespace. and there is a problem when I use auto-load.
ROOT/Application/Instance.php
<?php
namespace Application;
class Instance {
public static $_database;
public function __construct() {
self::$_database = new \Application\Module\Database();
}
public static function database() {
return self::$_database;
}
public static function ID(){
return md5(uniqid(mt_rand(), TRUE) . mt_rand() . uniqid(mt_rand(), TRUE));
}
public static function autoload($_className) {
$thisClass = str_replace(__NAMESPACE__.'\\', '', __CLASS__);
$baseDir = __DIR__;
if (substr($baseDir, -strlen($thisClass)) === $thisClass) {
$baseDir = substr($baseDir, 0, -strlen($thisClass));
}
$_className = ltrim($_className, '\\');
$fileName = $baseDir;
$namespace = '';
if ($lastNsPos = strripos($_className, '\\')) {
$namespace = substr($_className, 0, $lastNsPos);
$_className = substr($_className, $lastNsPos + 1);
$fileName .= str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $_className) . '.php';
if (file_exists($fileName)) {
require $fileName;
}
}
public static function registerAutoloader() {
spl_autoload_register(__NAMESPACE__ . "\\Instance::autoload");
}
}
ROOT/Application/Module/Database.php
<?php
namespace Application\Module;
include 'FluentPDO/FluentPDO.php';
class Database extends Module {
public static $_instance;
public function __construct() {
if(self::$_instance === NULL) {
self::$_instance = new FluentPDO(new PDO("mysql:host=8273639.mysql.rds.aliyuncs.com;dbname=db", 'name', 'password'));
}
}
}
When I run this:
new \Application\Instance();
I got this error:
Fatal error: Class 'Application\Module\FluentPDO' not found in /mnt/www/airteams_com/public/Application/Module/Database.php on line 13
I'm pretty sure that 'FluentPDO/FluentPDO.php' exists. and the error shows a wrong path of the file. the right path is 'ROOT/Application/Module/FluentPDO/FluentPDO.php'
So how can i use a no namespace class in my situation? thanks.
When you are working with namespaces you must fully qualify each class unless it's a child of the current namespace.
As such the FluentPDO is probably on the root namespace which means you need to access it like such:
self::$_instance = new \FluentPDO(new \PDO("mysql:host=8273639.mysql.rds.aliyuncs.com;dbname=db", 'name', 'password'));
I have a PHP script which is producing the following error
Parse error: syntax error, unexpected '[', expecting ')' in /home/masked/public_html/masked/AutoLoader.php on line 20
(note that I masked some parts of the directory given as they correspond with personal info.)
(line 20 is spl_autoload_register([$autoloader, 'load']); found in the register function.
I am running PHP 5.5
I have also tried it with PHP 5.3.27 and get the exact same result.
code bellow
run.php
require_once 'AutoLoader.php';
AutoLoader::register('src');
AutoLoader.php
/**
* A basic PSR style autoloader
*/
class AutoLoader
{
protected $dir;
protected $ext;
public function __construct($dir, $ext = '.php')
{
$this->dir = rtrim($dir, DIRECTORY_SEPARATOR);
$this->ext = $ext;
}
public static function register($dir, $ext = '.php')
{
$autoloader = new static($dir, $ext);
spl_autoload_register([$autoloader, 'load']);
return $autoloader;
}
public function load($class)
{
$dir = $this->dir;
if ($ns = $this->get_namespace($class)) {
$dir .= DIRECTORY_SEPARATOR.str_replace('\\', DIRECTORY_SEPARATOR, $ns);
}
$inc_file = $dir.DIRECTORY_SEPARATOR.$this->get_class($class).$this->ext;
if (file_exists($inc_file)) {
require_once $inc_file;
}
}
// Borrowed from github.com/borisguery/Inflexible
protected static function get_class($value)
{
$className = trim($value, '\\');
if ($lastSeparator = strrpos($className, '\\')) {
$className = substr($className, 1 + $lastSeparator);
}
return $className;
}
// Borrowed from github.com/borisguery/Inflexible
public static function get_namespace($fqcn)
{
if ($lastSeparator = strrpos($fqcn, '\\')) {
return trim(substr($fqcn, 0, $lastSeparator + 1), '\\');
}
return '';
}
}
On run.php try:
require_once('Autoloader.php');