Web Hosting Talk







View Full Version : PHP - how to dynamically access static class methods?


grabmail
04-03-2006, 11:47 AM
i have a function that needs to access the static methods of different classes

function x ($class)
{
$class::spit();
}

so. eg. x('Man') will access Man::spit() or x('Girl') will access Girl::spit()

The above code gives out an error. WHat is the right way to do it?

laserlight
04-03-2006, 12:06 PM
Shouldnt you use inheritance and polymorphism?

Azavia
04-03-2006, 12:47 PM
Which error does it give? That might help a bit more.

slack
04-03-2006, 01:43 PM
Maybe something like this:

// base class
class person {
function spit() {
return "you forgot to override me";
}
}

class man extends person {
function spit() {
return "man spit";
}
}

class woman extends person {
function spit() {
return "girl spit";
}
}


function x($obj) {
return $obj->spit();
}

$a_dude = new man;
echo x($a_dude); // will echo "man spit"

bilalk
04-03-2006, 03:05 PM
"call_user_func()" may be what you're looking for:
http://us3.php.net/manual/en/function.call-user-func.php

The second example there seems to apply.