Home > Back-end >  how to create a class from a variable in PHP?
how to create a class from a variable in PHP?

Time:08-01

I'd like to create some classes in a loop, I give the name of the class in a variable.
I get an error:
Fatal error: Uncaught Error: Class name must be a valid object or a string in ...
How can I do this?

<?php

$xml = simplexml_load_file('routes.xml');

$routes = $xml->Route;

    for($i =0; $i<count($routes); $i  ){

        $uri = $routes[$i]->attributes()->uri;
        $name = $routes[$i]->attributes()->name;


        Route::set($uri, function(){
            $name::CreateView();
        });

    }
?>

File XML

<?xml version="1.0" encoding="utf-8" ?>
<Routes>
    <Route name="Home" uri="" controller="Home"/>
    <Route name="AboutMe" uri="o-mnie" controller="AboutMe"/>
    <Route name="Interests" uri="o-mnie/zainteresowania" controller="AboutMe" method="interests"/>
    <Route name="Contact" uri="kontakt" controller="Contact"/>
</Routes>

CodePudding user response:

When you fetch attributes from a SimpleXML document, the return value is a SimpleXMLElement.

So if you were to var_dump($name) you would get something like...

class SimpleXMLElement#8 (1) {
  public ${0} =>
  string(4) "Home"
}

This cast is done usually implicitly when a method knows it needs a string, so but in this case it doesn't. The easiest way is to cast this to a string...

$name = (string)$routes[$i]->attributes()->name;

Your second problem is a general scope error ( a good explanation is at Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?)...

Route::set($uri, function() use ($name) {
        $name::CreateView();
    });
  • Related