1

I'm building a PHP project and I came across this problem I want to define a class by a string with the name of it and as far as I saw online I can do that but I'm having a problem doing that here's the code that doesn't work:

require_once Application::$ROOT_DIR.'/migrations/'.$migration;

$className = pathinfo($migration, PATHINFO_FILENAME);
var_dump($className);
$instance = new $className();

whenever I'm executing the code I'm getting the following error:

Uncaught Error: Class "m0001_initial" not found in 'my project path'

but whenever I try using the name of class in a direct way like that:

require_once Application::$ROOT_DIR.'/migrations/'.$migration;
$className = pathinfo($migration, PATHINFO_FILENAME);
var_dump($className);
$instance = new m0001_initial();

it works just fine so what could be the problem ?? note that whenever I run var_dump($className); the result is

string(13) "m0001_initial"

9
  • How did you load/include the file that actually contains the definition of the m0001_initial class? Commented Sep 14, 2022 at 12:26
  • Not reproducible based on the available info: 3v4l.org/jQOBe . So I'd agree with the above, possibly the file containing the class isn't included properly - the error seems to be about finding the class you mentioned, not a problem with the name you're generating being wrong. Although admittedly that doesn't really explain why it would work if you hard-code the class name, are you sure nothing else is changed at the same time when you try that? Commented Sep 14, 2022 at 12:28
  • here's how I loaded the file require_once Application::$ROOT_DIR.'/migrations/'.$migration; Commented Sep 14, 2022 at 12:38
  • 1
    Are there any namespaces involved in the project? e.g. the class name might actually be Acme\FooBar\m0001_initial? You could try var_dump( m0001_initial::class ); to get its fully qualified name Commented Sep 14, 2022 at 15:01
  • 1
    That's your problem then: namespaces in PHP are only expanded at compile-time; to reference a class dynamically at runtime, you need to spell out its fully qualified name, regardless of what namespace and use statements are in effect on that line of code. Commented Sep 14, 2022 at 20:09

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.