user3531149
user3531149

Reputation: 1539

Get object name as string on php?

So I got this source code

//get activated bundles
$bundle_list = new AutoRouter('dev',true);
$bundle_list = $bundle_list->getActivatedBundles(); 

for($a =0; $a < sizeof($bundle_list); $a++)
{
    var_dump($bundle_list[$a]);
}

The dump returns several objects like this

object(Symfony\Bundle\FrameworkBundle\FrameworkBundle)[38]
  protected 'name' => null
  protected 'extension' => null
  protected 'path' => null
  protected 'container' => null

object(Symfony\Bundle\SecurityBundle\SecurityBundle)[41]
  protected 'name' => null
  protected 'extension' => null
  protected 'path' => null
  protected 'container' => null

object(Symfony\Bundle\TwigBundle\TwigBundle)[40]
  protected 'name' => null
  protected 'extension' => null
  protected 'path' => null
  protected 'container' => null

I need to extract the object names as string like this:

(string) "Symfony\Bundle\FrameworkBundle\FrameworkBundle"
(string) "Symfony\Bundle\SecurityBundle\SecurityBundle"
(string) "Symfony\Bundle\TwigBundle\TwigBundle"

Something like

for($a =0; $a < sizeof($bundle_list); $a++)
{
    var_dump((string) $bundle_list[$a]);
}

Upvotes: 3

Views: 9897

Answers (2)

Alex
Alex

Reputation: 1

This is a different, but the keywords of the topic is the same:

function aObjName( $v , $get_class_var_name = false) {
    $trace = debug_backtrace();
    $vLine = file( __FILE__ );
    $fLine = $vLine[ $trace[0]['line'] - 1 ];
    $pattern = '/aObjName\(\$(.*?)->(.*?)\)/';
    preg_match($pattern, $fLine, $matches);
    if($get_class_var_name == false){
        if(!empty($matches[2])){
            return $matches[2];
        }
    } else {
        if(!empty($matches[1])){
            return $matches[1];
        }
    }
}

Try the following:

$model->objname = "objvalue";
echo aObjName($model->objname); // echo "objname"
echo aObjName($model->objname, true); // echo "model"

Upvotes: 0

Abdoul Ndiaye
Abdoul Ndiaye

Reputation: 193

You have several way to print a a class name in php:

  1. get_class: Returns the name of the class of an object. You will have a warning if the function is called on a non object

  2. ClassName::class: Since PHP 5.5, we can access to the fully qualified name of a class.

Hope this helps you.

Upvotes: 6

Related Questions