Reputation: 173
I want PHP to construct an object by indirect variable reference within namespaces. It goes like:
$ArticleObjectIdentifier = 'qmdArticle\excursions_list_item';
$result = new $ArticleObjectIdentifier($parent_obj,$r);
Where qmdArticle is a namespace used and excursions_list_item is the class name - which is usually not hardcoded but read from DB.
I get the following error - when using the above:
Class 'qmdArticle\\excursions_list_item' not found in /media/work/www/mytestarea/control.php on line 1916 ...
index.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();
?>
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; } }
?>
Upvotes: 0
Views: 183
Reputation: 173
I finally have found a similar example but it took a while until I actually got it:
The actual trick is using double quotes: >>"<< AND double-slashes >>\<< AND it doesn't work with an alias created like
use hy_soft\qimanfaya\testarea\articles as article;
You have to use the fully qualified class name (FQCN)
$ArticleLoader = "\\hy_soft\\qimanfaya\\testarea\articles\\excursions_list_item";
I would still apreciate any advice how to do it with an alias. Thanks.
Working example: 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;
}
}
?>
index.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();
?>
Upvotes: 0