PHP: instantiating a class from a variable is not performed oddly

I'm trying to instantiate a class (Laravel3 Eloquent model) of a variable, and I get a message stating that the class was not found.
However, when I hardcode the class name, it works fine.
(FYI, the code below $contact_typeis expected to either phone, fax, or email.)

Here is what I'm playing now:

    foreach( $input AS $contact_type => $contact_info )
    {
        foreach( $contact_info AS $data )
        {
            $obj = new $contact_type( (array)$data);
            echo'<pre>Obj: ',print_r($obj),'</pre>';  // <----- For Testing
        }
    }

When I run the code as above, it gives the error 'Class' Phone' not found .
When I replace new $contact_type()with new Phone()(or fax or email), it works fine.
I bet something simple, I just look :) What am I missing?
Please help!

+1
1

, , . :

, . , .

:

class Phone {}
$classtype = 'Phone';
$phone = new $classtype();
var_dump($phone);

:

object(Phone)#1 (0) {
}

, ( "" ) , ). :

class Phone {}
$classtype = 'Phone';
$reflectionClass = new ReflectionClass($classtype);
$phone = $reflectionClass->newInstanceArgs();
var_dump($phone);

Phone , :

Phone.php

<?php namespace Contact;

class Phone {}

test.php

<?php

include 'Phone.php';

$classtype = 'Contact\Phone';
$phone = new $classtype();
var_dump($phone);

100%, , , . :

<?php namespace Foo;

use SomePackage\SomeClass as WeirdName;

$test = new WeirdName();

:

<?php namespace Foo;

use SomePackage\SomeClass as WeirdName;

$class = 'WeirdName';
$test = new $class();

PHP , , WeirdName - SomePackage\Someclass? , , , userland, .

+4

Source: https://habr.com/ru/post/1624293/


All Articles