2

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 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that make sense. I had read the docs, but I wasn't able to put that together from them. So I'm glad you added a quick explanation of what they meant.
0

You can use:

$alias = $userType . 'LoginPage';
class_alias('Page\Acceptance\Users\Login', $alias);
$User = new $alias();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.