1

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);
}

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.