Search code examples
phpnamespaces

PHP object to array without namespace


I want to cast objects to arrays. The default casting solution has strange behavior; it prepends object (class) namespaces to the property names!

My code:

$assoc = (array) $product;
print_r($assoc);

The output:

[App\Model\Productid] = 1
[App\Model\Productname] = Samsung Galaxy S3
[App\Model\Productprice] = 120

What I need:

[id] = 20568
[name] = Samsung Galaxy S3
[price] = 120

Solution

  • $obj = new \ReflectionObject($product); 
    print_R($obj->getName());  // get namespace and class name here