Jump to content

[SOLVED] variable as classname


TiloW

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
Share on other sites

true.. but in some situations this string is interpreted as a classname - i've provided one example above.

Is there any other way to store classes in variables?

Why does the instantiation work, but not the call of a static method?!

Link to comment
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();");

Link to comment
Share on other sites

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?

 

Anyway.. the eval function is exactly what i was looking for!

 

thanks Crayon =)

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.