0

我希望 PHP 通过命名空间内的间接变量引用来构造一个对象。它是这样的:

$ArticleObjectIdentifier = 'qmdArticle\excursions_list_item';
$result = new $ArticleObjectIdentifier($parent_obj,$r);

其中 qmdArticle 是使用的命名空间,而 excursions_list_item 是类名——通常不是硬编码的,而是从数据库中读取的。

我收到以下错误 - 使用上述内容时:

Class 'qmdArticle\\excursions_list_item' not found in /media/work/www/mytestarea/control.php on line 1916 ...

索引.php

  <?php
namespace hy_soft\qimanfaya\testarea\main;

use hy_soft\qimanfaya\testarea\articles as article;

include_once('article.php');
$ArticleLoader = 'article\excursions_list_item';
$article = new $ArticleLoader();
$article->showcontent();


?>

文章.php

<?php namespace hy_soft\qimanfaya\testarea\articles

  class excursions_list_item {  private $content;       function
 __construct()  {
          $this->content = 'This is the article body';

         // parent::__construct($parent,$dbrBaseRec);
            }

    public function showcontent()   {       echo $this->content;    } } 
?>
4

1 回答 1

0

我终于找到了一个类似的例子,但我花了一段时间才真正得到它:

实际的技巧是使用双引号: >>"<< AND 双斜杠 >>\<< AND 它不适用于创建的别名,如

use hy_soft\qimanfaya\testarea\articles as article;

您必须使用完全限定的类名 (FQCN)

$ArticleLoader = "\\hy_soft\\qimanfaya\\testarea\articles\\excursions_list_item";

我仍然会感谢任何建议如何使用别名来做到这一点。谢谢。

工作示例:article.php

<?php
namespace hy_soft\qimanfaya\testarea\articles;

class excursions_list_item
{
    private $content;

    function __construct()
    {
         $this->content = 'This is the article body';

        // parent::__construct($parent,$dbrBaseRec);

    }

    public function showcontent()
    {
        echo $this->content;
    }
}
?>

索引.php

<?php
namespace hy_soft\qimanfaya\testarea\main;

use hy_soft\qimanfaya\testarea\articles as article;

include_once('article.php');
$ArticleLoader = "\\hy_soft\\qimanfaya\\testarea\articles\\excursions_list_item";
//$ArticleLoader = "\\article\\excursions_list_item"; doesn't work
$article = new $ArticleLoader();
$article->showcontent();


?>
于 2014-12-21T12:48:53.517 回答