user1513171
user1513171

Reputation: 1974

PHP ReflectionClass - Fatal error: Class name must be a valid object or a string

I cannot seem to get around this error when I'm trying to create an Object using Reflection and get this error every time.

Here's my code:

public static function getMapper($klass) {
    echo $klass;
    if(class_exists($klass)) {
        echo "YES!";
    } else {
        echo "NO!";
    }

    $mapperClass = new \ReflectionClass($klass);
    print_r($mapperClass);
    return new $mapperClass->newInstance();
}

The first echo prints "\domain\Member". This is correct as it is what I passed in and it's the class I'm trying to create an Object of.

Next, the echo prints "YES". The class exists!

Next, I pass $klass into ReflectionClass and...

The next print_r prints:

ReflectionClass Object ( [name] => domain\Member )

Notice the \ before domain is gone. Could be part of the problem?

Then, when I call newInstance() I get the error.

Fatal error: Class name must be a valid object or a string in C:\Users\Zack\PhpstormProjects\MyApp\base\Registry.php on line 53

So I don't know what the problem is. The Member class exists in the domain namespace. Just in case maybe something in Member is wrong, here it is; not much yet:

<?php

namespace domain;

use base\Registry;
use domain\base\BaseMember;

class Member extends BaseMember {

/**
 * @param $displayName
 * @return Member
 */
public static function findMemberByDisplayName($displayName) {
    return Registry::memberRepository()->findMemberByDisplayName($displayName);
}

Upvotes: 1

Views: 14789

Answers (1)

jcsanyi
jcsanyi

Reputation: 8174

You don't need the new in the final line. It should be this instead:

return $mapperClass->newInstance();

What's actually happening, is you're getting an instance of Member, and then passing that instance as a classname to new. So PHP is seeing return new {instance of Member}, and it's complaining that the instance of the object is not a valid classname.

Upvotes: 4

Related Questions