简体   繁体   中英

how do you cast from a const string namespace

Im trying to figure out a way to easily cast a dynamically created object so i can see its properties and exposed methods in my IDE. It seems to be acting weird when the string includes a fully qualified namespace.

Is there anyway I can cast objects from a const string in an abstract class ??

abstract class Models
{
    const MODEL = "foo\\bar\\Model";
}


//OK
    $p1 = "foo\\bar\\Model";
    $p2 = new $p1; 

//FAILS

    //$wannaDoThis = (Models::MODEL) Generator::generate(Models::MODEL);


    //$str1 = Models::MODEL;
    //$str2 = (string) Models::MODEL;
    //$o1 = new Models::MODEL;
    //$o2 = new "".Models::MODEL;
    //$o3 = new (Models::MODEL);

This should work:

<?php

namespace foo\bar;

class Model
{
}

namespace SomeOtherNamespace;

abstract class Models
{
    const MODEL = "foo\\bar\\Model";
}

$class = Models::MODEL;
$x = new $class();
var_dump($x);

Which you can see here https://3v4l.org/87sKs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM