0

I'm having trouble with calling a class within the same namespace dynamically.

To simplify my system:

I have this namespace structure:

core
core\classes

In core\classes there are two classes (in two files, both were included before):

class AUTO_LOAD
{
        public function regSingleton($event)
        {
            $temp_event = $event;
            //$event = '_' . $event;
            //global $$event;
            //$$event = $temp_event::newInst(); // the old version without namespaces - this worked
            HELPER::varDump(SYSTEM::newInst()); // this works
            HELPER::varDump($temp_event::newInst()); // this doesn't work
            exit;
        }
}

and

class SYSTEM
{
     // Some code;
}

Then instantiate AUTO_LOAD:

$_AUTO_LOAD = new AUTO_LOAD;
$_AUTO_LOAD->regSingleton('SYSTEM');

Output:

object(core\classes\SYSTEM)#2 (3) {}

Fatal error: Class 'SYSTEM' not found in .../system/includes/classes/class.autoload.php

As you can see above if I try to call SYSTEM::newInst() (statically) it works, but if I try to run it dynamically ($temp_event::newInst()) it doesn't.

Neither a direct call via '\\' . __NAMESPACE__ . '\\' . $temp_event::newInst(); nor via '\\core\classes\\' . $temp_event::newInst(); works (same output).

Where is the error (in reasoning)? Thanks for any help in advance!

PS: I already read PHP namespace with Dynamic class name but I can't see the difference?

1 Answer 1

1

As the scope resolution operator (::) has higher precedence than concatenation (.) your direct call '\\' . __NAMESPACE__ . '\\' . $temp_event::newInst(); will be evaluated as ('\core\classes\') . ('SYSTEM'::newInst()) and therefore won't work.

Try changing your code into this:

$temp_event = __NAMESPACE__ . '\\'  . $event;

That will have $temp_event include the namespace and $temp_event::newInst() will be evaluated as 'core\classes\SYSTEM'::newInst(), i.e. core\classes\SYSTEM::newInst().

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! But I'm still not sure why $temp_event::newInst(); isn't working when $temp_event = 'SYSTEM';* as SYSTEM` is in the same namespace like AUTO_LOAD?
I don't know the internals of the PHP but the manual states that "One must use the fully qualified name (class name with namespace prefix)" when dynamically accessing namespaced elements. You can read a little more about it in the PHP manual at php.net/manual/en/language.namespaces.dynamic.php .
Good point, I seem to overread that. Thank you once again, you saved my day!

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.