Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with PHP namespaces and built-in classes, how to fix?

Tags:

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

like image 666
WoodyTheHero Avatar asked Aug 01 '11 16:08

WoodyTheHero


People also ask

What is the best approach for working with classes and namespaces in 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.

What problems has namespace solved in PHP?

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.

How do namespaces work in PHP?

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.

Which of the following elements are affected by namespaces in PHP?

only four types of code are affected by namespaces: classes, interfaces, functions and constants.


2 Answers

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.

like image 117
hakre Avatar answered Oct 13 '22 06:10

hakre


Add a backslash before class name, ie

$db = new \PDO(params); 
like image 30
ain Avatar answered Oct 13 '22 07:10

ain