Page 1 of 1

Magically Finding a class

Posted: Mon Oct 04, 2010 11:41 am
by zoborg
Hello folks,

Sorry if my questions are a little lame, I am a Perl dev at heart and am doing some projects in Zend/PHP!, this is a much simpler problem than I want to solve, but basically I want to be able to dynamically resolve class names and call as static method on that class.


lets say

Code: Select all

class Person extends MyBaseClass {
       public static  $_test = 'Person';
       public static function tell() {
            echo Person::$_test;
      }
}
class Item  extends MyBaseClass {
       public static $_test = "Item";
      
       public static function tell() {
            echo Item::$_test;
      }
}
So I could of course do Item::tell(); or Person::tell();

However I want to factor out the 'tell' function to the MyBaseClass as its common to both, however how would I automagically call the correct static class name? if that makes sense?

I tried a experiment like '

Code: Select all

$class = 'Person';
$class::tell();
But that gives a error?

Any ideas?
$

Re: Magically Finding a class

Posted: Mon Oct 04, 2010 12:04 pm
by John Cartwright
You can get the class name from the parent function using

Code: Select all

get_class($this);
EDIT | Just realized you are using static methods, therefore, you need to use PHP >= 5.3 feature called Late Static Bindings

Code: Select all

class Parent 
{
   static public function myAction()
   {
      echo get_called_class();
   }
}

class Child extends Parent
{
}

Child::myAction(); //echo's Child
EDIT2 | If you are not using the latest version of PHP, you could probably hack up a debug_backtrace() workaround

Re: Magically Finding a class

Posted: Mon Oct 04, 2010 12:06 pm
by Jonah Bron
Couldn't you just call self::_test ?

Re: Magically Finding a class

Posted: Mon Oct 04, 2010 12:09 pm
by John Cartwright
Jonah Bron wrote:Couldn't you just call self::_test ?
If you have 5.3, there is no reason to implement the a hardcoded variable of the class name. However, your right though, the the current implementation it would make more self the use the self keyword.

Re: Magically Finding a class

Posted: Mon Oct 04, 2010 1:46 pm
by AbraCadaver
You can use self if you are calling from in the class, but if outside:

Code: Select all

$class = 'Person';
call_user_func(array($class, 'tell'));
//or
call_user_func("$class::tell");

Re: Magically Finding a class

Posted: Mon Oct 04, 2010 4:18 pm
by Eran
It's probably better if you avoid this kind of dynamic static classes. Use objects and regular inheritance instead