Reputation: 21
I have prepared a simple php class with one constructor. In this same file I have also initalized the class. Everything works fine until the namespace is activated. Below script works fine.
<?php
require_once('../inc/settings.inc.php');
class Auth
{
private $pdo;
private $stmt;
public function __construct ()
{
try {
$this->pdo = new PDO(PCC_DRIVER . ':host=' . PCC_HOST . ';dbname=' . PCC_DB, PCC_USER, PCC_USER_PASS);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->pdo->query('SET names utf8');
$this->pdo->query('SET character_set_client = utf8');
$this->pdo->query('SET character_set_results = utf8');
$this->pdo->query('SET character_set_connection = utf8');
$this->pdo->query('SET character SET utf8');
}
catch (Exception $ex)
{
echo 'Exception -> ';
var_dump($ex->getMessage());
}
$this->stmt = $this->pdo->prepare("SELECT * FROM klienci");
$this->stmt->execute();
while ($row = $this->stmt->fetch())
{
echo $this->x=$row['name']."<br />\n";
}
}
}
$auth = new Auth();
echo $auth;
The record was returned.
But when including the namespaces it stopped.
<?php
namespace Pcc\System;
require_once('../inc/settings.inc.php');
class Auth
{
private $pdo;
private $stmt;
public function __construct ()
{
try {
$this->pdo = new PDO(PCC_DRIVER . ':host=' . PCC_HOST . ';dbname=' . PCC_DB, PCC_USER, PCC_USER_PASS);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->pdo->query('SET names utf8');
$this->pdo->query('SET character_set_client = utf8');
$this->pdo->query('SET character_set_results = utf8');
$this->pdo->query('SET character_set_connection = utf8');
$this->pdo->query('SET character SET utf8');
}
catch (Exception $ex)
{
echo 'Exception -> ';
var_dump($ex->getMessage());
}
$this->stmt = $this->pdo->prepare("SELECT * FROM klienci");
$this->stmt->execute();
while ($row = $this->stmt->fetch())
{
echo $this->x=$row['name']."<br />\n";
}
}
}
$auth = new Pcc\System\Auth();
echo $auth;
The browser returned Error 500. Do you know why it happens ? Is it someting wrong ?
Upvotes: 0
Views: 235
Reputation: 158
The Error says Class 'Pcc\System\PDO' not found.
It means it is looking for class PDO in the Pcc\System namespace (relative path). It is because you did not tell your program to look from the root (absolute path).
Try
$this->pdo = new \PDO(PCC_DRIVER . ':host=' . PCC_HOST . ';dbname=' . PCC_DB, PCC_USER, PCC_USER_PASS);
and
$auth = new \Pcc\System\Auth();
Upvotes: 1
Reputation: 649
$auth = new Pcc\System\Auth();
instead try
new Auth();
only.
Also please define the classes you want to use below namespace like :
use PDO;
Upvotes: 1