简体   繁体   English

如何从const字符串名称空间进行转换

[英]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. 我试图找到一种方法来轻松地投射动态创建的对象,以便可以在我的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 ?? 无论如何,我可以在抽象类中从const字符串强制转换对象吗?

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 您可以在这里看到https://3v4l.org/87sKs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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