Mgccl Posted February 8, 2007 Share Posted February 8, 2007 variable functions ,like this $somefunc = 'rand' $somefunc(0,1); output either 0 or 1 But it does not work on classes, like class coolclass{ var $somefunc = 'rand'; } $cool = new coolclass; $cool->somefunc(0,1); it tell you an error, say there is no such method defined. of course this can be simplely defeated in my next example: class coolclass{ var $somefunc = '$this->got_called'; } function call_func(){ $a = $this->somefunc;//$this->got_called; $a(); } function got_called(){ echo 'yeeeah'; } $cool = new coolclass; $cool->call_func(); This one uses a method, even it does not call on a function by using a variable function directly, it uses a variable to store the function name, so it is good too . But this time, it is calling a method in the class, and it does not work. Any suggestions on how to call a class method like a variable function inside a class? I saw one can do it outside a class. http://www.java2s.com/Code/Php/Class/Callclassmethoddynamically.htm Link to comment https://forums.phpfreaks.com/topic/37584-call-on-a-class-method-dynamically-inside-a-class-like-variable-function/ Share on other sites More sharing options...
scott212 Posted February 8, 2007 Share Posted February 8, 2007 I think it's a lot simpler than your making it. Try something like this: class randNum { function genRand($rand1,$rand2) { $rand = rand($rand1,$rand2); return $rand; } } $randClass = new randNum; $randNum = $randClass->genRand(0,1); echo $randNum; OR if you wanted to have a set top or bottom you would do this: class genRand { var $randTop; #constructor function genRand() { $this->randTop = 1; } function genRand($randBottom) { $rand = rand($randBottom,$this->randTop); return $rand; } } $randClass = new genRand; $randNum = $randClass->genRand(0); echo $randNum; Hope that helps Link to comment https://forums.phpfreaks.com/topic/37584-call-on-a-class-method-dynamically-inside-a-class-like-variable-function/#findComment-179722 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.