I'm writing a small library in PHP and i'm having some problems with built-in classes not being read. For example:
namespace Woody; class Test { public function __construct() { $db = new PDO(params); } }
This gives me:
PHP Fatal error: Class 'Woody\PDO' not found in /var/www/test.php
To address this problem, namespaces were introduced in PHP as of PHP 5.3. The best way to understand namespaces is by analogy to the directory structure concept in a filesystem. The directory which is used to group related files serves the purpose of a namespace.
Namespaces are qualifiers that solve two different problems: They allow for better organization by grouping classes that work together to perform a task. They allow the same name to be used for more than one class.
Like C++, PHP Namespaces are the way of encapsulating items so that same names can be reused without name conflicts. It can be seen as an abstract concept in many places. It allows redeclaring the same functions/classes/interfaces/constant functions in the separate namespace without getting the fatal error.
only four types of code are affected by namespaces: classes, interfaces, functions and constants.
This:
namespace Woody; use PDO;
Or:
$db = new \PDO(params);
Point in case is, that the class PDO
is not a full qualified name within your Namespace, so PHP would look for Woody\PDO
which is not available.
See Name resolution rulesDocs for a detailed description how class names are resolved to a Fully qualified name.
Add a backslash before class name, ie
$db = new \PDO(params);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With