【问题标题】:setFetchMode to type Class using namespaces in PHPsetFetchMode 在 PHP 中使用命名空间键入 Class
【发布时间】:2013-07-30 13:17:17
【问题描述】:

我正在尝试使用 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
?>

【问题讨论】:

    标签: php pdo


    【解决方案1】:

    如果您使用早于 5.5 的 PHP

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

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

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

    如果您使用的是 PHP 5.5

    你很幸运!新的::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);
    

    【讨论】:

    • 希望我可以升级到 PHP 5.5... :-)
    • 我无法让这些方法中的任何一个起作用。我尝试的第一件事是 'myproject\page\Page' 但这不起作用。
    • 有什么方法可以让我使用 Mysqli 而不是 PDO 来实现类似的目标?
    • @AndrewCookson:我不确定这是否会有所不同,但是在前面添加另一个斜杠怎么样? \myproject\...。对于 mysqli,fetch_object 有一个允许您指定类的参数。
    • @Jon,前导斜杠无效,脚本报告:致命错误:在非对象上调用成员函数 getDateAdded()。我会调查 fetch_object。可惜 PDO 不起作用。
    猜你喜欢
    • 1970-01-01
    • 2019-03-11
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 2011-05-08
    • 2013-12-28
    • 2023-03-24
    • 2016-01-05
    相关资源
    最近更新 更多