Jump to content

Recommended Posts

Hey guys =)

 

Here's my problem:

// exemplary class
class Test
{
  static public DoSomething()
  {}
}

// reference of class "Test"
$testClassName = "Test";

// create new instance of class "Test"
$testInstance = new $testClassName();  // works just fine

// call static method of class "Test"
$testClassName::DoSomething(); // doesn't work

 

So.. How can i call a static method of a class which is strored in a variable?

 

Thanks for any help =)

Link to comment
https://forums.phpfreaks.com/topic/165696-solved-variable-as-classname/
Share on other sites

That's not an example of of a string being interpreted as a class name. That's an example of storing a string of value "Test" to a variable $testClassName.  If you want to reference a static method like that, you can do

 

Test::doSomething();

 

or else like

 

$testClassName = "Test";

eval($testClassName."::doSomething();");

Well.. I don't really get the difference because in

$testInstance = new $testClassName();

the value of $testClassName is interpreted as a name of a class ..isn't it?

 

No.  Class names (and functions) are not parsed inside quotes like that.  Only variables arrays and objects.

Why does what work...this?

Well.. I don't really get the difference because in

$testInstance = new $testClassName();

the value of $testClassName is interpreted as a name of a class ..isn't it?

 

edit:

 

Accidentally hit post.  It does work, because it will create an instance of the object using the value of that variable.  But that is not the same as linking that variable to the class, or somehow making an object out of a variable.  You are simply making use of the value.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.