0
0
PHPprogramming~20 mins

Aliasing with as keyword in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
PHP Aliasing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of aliased class usage
What is the output of this PHP code using aliasing with the as keyword?
PHP
<?php
namespace Animals;
class Dog {
    public function speak() {
        return "Woof!";
    }
}

namespace Pets;
use Animals\Dog as PetDog;

$dog = new PetDog();
echo $dog->speak();
?>
AWoof!
BFatal error: Class 'Pets\Dog' not found
CWoof Woof!
DError: Cannot use 'as' outside namespace
Attempts:
2 left
💡 Hint
Look at how the use statement renames the class from another namespace.
Predict Output
intermediate
2:00remaining
Aliasing function import output
What will this PHP code output when using aliasing with the as keyword for functions?
PHP
<?php
namespace Utils;
function greet() {
    return "Hello!";
}

namespace Main;
use function Utils\greet as sayHello;

echo sayHello();
?>
AHello!
BFatal error: Call to undefined function sayHello()
CSyntax error: unexpected 'as'
DHello Hello!
Attempts:
2 left
💡 Hint
Check how the function is imported with an alias.
🔧 Debug
advanced
2:00remaining
Identify the error in aliasing a constant
This PHP code tries to alias a constant using the as keyword. What error will it produce?
PHP
<?php
namespace Config;
const VERSION = '1.0';

namespace App;
use const Config\VERSION as APP_VERSION;

echo APP_VERSION;
?>
AFatal error: Undefined constant APP_VERSION
BFatal error: Cannot use 'as' with const
CParse error: syntax error, unexpected 'as'
D1.0
Attempts:
2 left
💡 Hint
PHP supports aliasing constants with use const and as.
📝 Syntax
advanced
2:00remaining
Which aliasing syntax is invalid?
Which of the following PHP aliasing statements using as keyword is NOT valid syntax?
Ause Some\Namespace\ClassName as AliasName;
Buse Some\Namespace\ClassName alias ClassAlias;
Cuse const Some\Namespace\CONST_NAME as AliasConst;
Duse function Some\Namespace\funcName as aliasFunc;
Attempts:
2 left
💡 Hint
Check the correct keyword order and syntax for aliasing.
🚀 Application
expert
3:00remaining
Predict the output with multiple aliasing
Given this PHP code with multiple aliasing, what will be the output?
PHP
<?php
namespace A {
    class Test {
        public function msg() {
            return "From A";
        }
    }
}

namespace B {
    class Test {
        public function msg() {
            return "From B";
        }
    }
}

namespace Main {
    use A\Test as TestA;
    use B\Test as TestB;

    $a = new TestA();
    $b = new TestB();

    echo $a->msg() . ' & ' . $b->msg();
}
?>
AParse error: syntax error, unexpected 'use'
BFrom B & From A
CFrom A & From B
DFatal error: Cannot redeclare class Test
Attempts:
2 left
💡 Hint
Aliasing allows using two classes with the same name from different namespaces.