douan7529 2016-02-04 22:02
浏览 770
已采纳

PHP如何使用字符串实例化类别名

I know I can do this without the alias, but in this case trying to instantiate the object using an alias attempts to find a class by the alias name. Can this not be done in PHP?

// Import of manager, admin, etc login PageObjects
use Page\Acceptance\Users\Login as ManagerLoginPage;
use Page\Acceptance\Admins\Login as AdminLoginPage;

...

// Login user type snippet
$alias= $userType . 'LoginPage'; // produces ManagerLoginPage
$User = new $alias($this); // tries to instantiate a class named 'ManagerLoginPage', which doesn't exist

$User->{'loginAs' . $userType}($user);
  • 写回答

2条回答 默认 最新

  • doubi1797 2016-02-04 22:10
    关注

    As the documentation explains:

    The ability to refer to an external fully qualified name with an alias, or importing, is an important feature of namespaces. This is similar to the ability of unix-based filesystems to create symbolic links to a file or to a directory.

    And several paragraphs below:

    Importing is performed at compile-time, and so does not affect dynamic class, function or constant names.

    This means that when you write:

    use Page\Acceptance\Users\Login as ManagerLoginPage;
    $page = new ManagerLoginPage();
    

    PHP expands the aliases during the compilation to:

    $page = new \Page\Acceptance\Users\Login();
    

    You have to put the complete class name (including all the containing namespaces) into the variable $alias to make it work:

    $alias = 'Page\Acceptance\Users\Login';
    $User = new $alias($this);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • dongzheng4556 2016-02-04 22:16
    关注

    You can use:

    $alias = $userType . 'LoginPage';
    class_alias('Page\Acceptance\Users\Login', $alias);
    $User = new $alias();
    
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:我在自己的电脑上运行起来总是报错(开发工具-github)
  • ¥40 基于51单片机实现球赛计分器功能
  • ¥15 cs2游戏画面卡住,应用程序sid与指挥者sid不匹配
  • ¥15 实验七:Pandas要有实验截图和代码
  • ¥15 TypeError: Make sure that the iterable only contains strings.
  • ¥35 电脑放图书馆,这是被黑了吗
  • ¥15 等高线中数据取消科学计数法
  • ¥15 Qt播放10路ffmpeg 视频流
  • ¥15 如何利用闲置机械硬盘变现
  • ¥15 信号处理中的凸优化问题