Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to call a static method for a namespaced class from another class with the same namespace. But the other class' name is contained in a variable :

<?php 

namespace MyApp\Api;
use \Eloquent;

class Product extends Eloquent {

    public static function find($id)
    {
        //....
    }

    public static function details($id)
    {
        $product = self::find($id);
        if($product)
        {
            $type = $product->type; // 'Book'
            $product = $type::find($product->id);
            return $product;
        }
    }
}

Here is the Book class :

<?php

namespace MyApp\Api;
use \Eloquent;

class Book extends Eloquent {

    public static function find($id)
    {
        //....
    }

}

My type variable contains a valid class name here Book. This class is in the same folder, and uses the same namespace. This code returns the error Class 'Book' not found. I have tried several variations (from the SO questions I found) using backslashes, or the call_user_func function, but nothing worked. Anyone knows what's wrong ?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

When using a variable to reference your class, you need to use a fully qualified name. Try this...

$type = __NAMESPACE__ . '\\' . $product->type;
$product = $type::find($product->id);
share|improve this answer
    
Awesome, that worked !!! Thanks man ! –  3rgo Jan 13 '14 at 7:23

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.