0

我正在尝试使用 setFetchMode 和 FETCH_CLASS 在 PHP 类中填充一些变量。

<?php # index.php
use myproject\user\User;
use myproject\page\Page;

$q = 'SELECT * FROM t';
$r = $pdo->query($q);

  // Set the fetch mode:
  $r->setFetchMode(PDO::FETCH_CLASS, 'Page');

 // Records will be fetched in the view:
 include('views/index.html');
?>

在我的视图文件中,我有:

<?php # index.html
// Fetch the results and display them:
while ($page = $r->fetch()) {
echo "<article>
<h1><span>{$page->getDateAdded()}</span>{$page->getTitle()}</h1>
<p>{$page->getIntro()}</p>
<p><a href=\"page.php?id={$page->getId()}\">read more here...</a></p>
</article>
";
}
?>

这些方法来自 Class: Page.php:

<?php # Page.php
function getCreatorId() {
 return $this->creatorId;
}
function getTitle() {
 return $this->title;
}
function getContent() {
 return $this->content;
}
function getDateAdded() {
 return $this->dateAdded;
}
?>

使用标准类时非常简单,也就是说,我已经一切正常;然而,名称空间似乎有问题。

例如,如果我使用:

<?php # index.php
require('Page.php'); // Page class
$r->setFetchMode(PDO::FETCH_CLASS, 'Page'); // works
?>

但是当使用命名空间时,

<?php # index.php
use myproject\page\Page;
?>
// Set the fetch mode:
$r->setFetchMode(PDO::FETCH_CLASS, 'Page'); // problem

// Records will be fetched in the view:
include('views/index.html');
?>

浏览到 index.php 和浏览器报告:

致命错误:在第 5 行的 /var/www/PHP/firstEclipse/views/index.html 中的非对象上调用成员函数 getDateAdded()

我的命名空间路径都设置正确,因为我已经使用上述命名约定成功地实例化了对象,例如:

<?php # index.php

use myproject\page\User; # class: /myproject/page/user/User.php
$b = new User();
print $b->foo(); // hello
?>
4

1 回答 1

3

如果您使用早于 5.5 的 PHP

您需要提供类的完全限定名称:

use myproject\page\Page;

$r->setFetchMode(PDO::FETCH_CLASS, 'myproject\page\Page');

不幸的是,您必须像这样重复自己(如果您决定Page从另一个命名空间切换到不同的类,这段代码会中断),但没有办法绕过丑陋。

如果您使用的是 PHP 5.5

你很幸运!new::class关键字旨在帮助解决这个问题:

// PHP 5.5+ code!
use myproject\page\Page;

// Page::class evaluates to the fully qualified name of the class
// because PHP is providing a helping hand
$r->setFetchMode(PDO::FETCH_CLASS, Page::class);
于 2013-07-30T13:18:59.677 回答