I have this:
function callMe()
{
// return $this->callMe();
return $this->__FUNCTION__();
}
This one doesn't work:
Fatal error: Call to undefined method Classss::__FUNCTION__()
But what if I don't want to duplicate the name of the method?
The following works, But I recommend not doing it.
class Test {
public function f() {
echo "called";
$fn_name = __FUNCTION__;
$this->$fn_name();
// Equally valid:
// $this->{__FUNCTION__}();
}
}
Try it this way:
function callMe( ){
return call_user_func(
array( $this, __METHOD__ )
//(optional) , $argument1, $argument2, ....
);
}
An apporach like this will work too.
<?php
callMe(0);
function callMe($count)
{
$count++;
echo $count . " ";
if($count > 10){
return;
}
call_user_func(__FUNCTION__, $count);
}
?>
Related
Take the following code example:
<?php
class A {
public function aa() {
$output = (array(&$this, 'ab'), $post_id);
return $output;
}
public function ab( $post_id ) {
//do stuff
}
}
?>
What's the correct way to call method ab that contains additional arguments like $post_id?
I know that the $output line doesn't work, but that's the line I'm stuck on.
Thanks.
Just this way:
$output = $this->ab($post_id);
Try this . May be this will help.
<?php
class A {
public function aa() {
$args = func_get_args();
$output = call_user_func_array(array($this,'ab'),$args);
// But this way the "ab" function have to be private
// Or you can simply do $output = $this->ab($post_id)
return $output;
}
public function ab( $post_id ) {
//do stuff
}
}
$a = new A();
$a->aa(162);
?>
I am trying to build a function that will call another function.
For example, if I have an array full of function names to call, is it possible to call a function for every array value without writing it in a script?
Example:
function email($val=NULL) {
if($val)
$this->_email = $val;
else
return $this->_email;
}
function fname($val=NULL) {
if($val)
$this->_fname = $val;
else
return $this->_fname;
}
For email, fname, etc.
But I want to have it like:
function contr_val($key,$val) {
function $key($val=NULL) {
if($val)
$this->_$key = $val;
else
return $this->_$key;
}
function $key($val="hallo");
}
And call it with:
contr_val("email", "test")
You're really trying to create member variables dynamically and retrieve their values. This is what __get() and __set() are for.
Here's how you could use it:
class TestClass {
var $data = array();
public function __set($n, $v) { $this->data[$n] = $v; }
public function __get($n) {
return (isset($this->data[$n]) ? $this->data[$n] : null);
}
public function contr_val($k, $v = NULL) {
if ($v)
$this->$k = $v;
else
return $this->$k;
}
};
$sherp = new TestClass;
$sherp->contr_val("Herp", "Derp");
echo "Herp is: " . $sherp->contr_val("Herp") . "\n";
echo "Narp is: " . $sherp->contr_val("Narp") . "\n";
Something like this:
/*
Input: $val - any value
$varname - the variable name, for instance: _email
*/
function checkValue($val=NULL, $varname) {
if($val)
$this->$var = $val;
else
return $this->$var;
}
checkValue("hello", "_email");
checkValue("hello2", "_name");
If you are doing this for a class, consider using PHP's magic methods __get() and
__set().
In an array full of function names, this calls every function that exists.
ghoti#pc:~$ cat functest.php
#!/usr/local/bin/php
<?php
function one() { print "one\n"; }
function two() { print "two\n"; }
function three() { print "three\n"; }
$a=array( "one", "two", "three", "four" );
foreach ($a as $item) {
if (function_exists($item)) {
$item();
} else {
print "No such function: $item\n";
}
}
ghoti#pc:~$ ./functest.php
one
two
three
No such function: four
ghoti#pc:~$
You need to check if the function exists or not:
function contr_val($key,$val) {
if (!function_exists($key)) {
function $key($val=NULL) {
if ($val)
$this->_$key = $val;
}
}
else {
return $this->_$key;
}
}
How can i pass a class as a parameter in my function
So far i've tried
$sc = new SampleClass();
SampleFunction($sc);
function SampleFunction(&$refClass)
{
echo $refClass->getValue();
}
this is a simplified example of what im doing.. i actually have to do complex procedures inside this sample function. I'm not getting any response from the sample function. What am i doing wrong? thank you
UPDATE
char.php
class Charss {
var $name=0;
var $hp=500;
var $spd=10;
var $rtime=10;
var $dmg=10;
function __construct( $name, $hp, $spd, $rtime , $dmg) {
$this->name = $name;
$this->hp = $hp;
$this->spd = $spd;
$this->rtime = $rtime;
$this->dmg = $dmg;
}
function get_name() {
return $this->name;
}
function set_name($new_name) {
$this->name = $new_name;
}
function get_hp() {
return $this->hp;
}
function set_hp($new_hp) {
$this->hp = $new_hp;
}
function get_spd() {
return $this->spd;
}
function set_spd($new_spd) {
$this->spd = $new_spd;
}
function get_rtime() {
return $this->rtime;
}
function set_rtime($new_rtime) {
$this->rtime = $new_rtime;
}
function get_dmg() {
return $this->get_dmg;
}
function set_dmg($new_dmg) {
$this->dmg = $new_dmg;
}
}
myclass.php
require("char.php");
class Person {
function try_process()
{
$chr1 = new Charss("Player1",500,3,0,50);
$chr2 = new Charss("Player2",500,6,0,70);
while ($chr1->get_hp() > 0 && $chr2->get_hp() > 0)
{
$sth = min($chr1->get_rtime(), $chr2->get_rtime());
if ($chr1->get_rtime() == 0 && $chr2->get_rtime() > 0)
{
exit;
Fight($chr1,$chr2);
$chr1->set_rtime($chr1->get_spd());
}
elseif ($chr2->get_rtime() == 0 && $chr1->get_rtime() > 0)
{
Fight($chr2,$chr1);
$chr2->set_rtime($chr2->get_spd());
}
else
{
Fight($chr1,$chr2); #having trouble with this
$chr1->set_rtime($chr1->get_spd());
}
$chr1->set_rtime($chr1->get_rtime() - $sth);
$chr2->set_rtime($chr2->get_rtime() - $sth);
}
}
function Fight($atk,$def)
{
$def->set_hp($def->get_hp() - $atk->get_dmg());
echo $atk->get_name() . " attacked " . $def->get_name() . " for " . $atk->get_dmg() . " damage";
}
}
so im calling the function try_process on button click
What you're actually doing there is passing an object, not a class.
$sc = new SampleClass();
creates an instance of SampleClass, aka an object.
I assume there's some error being thrown elsewhere as what you have is correct.
I tested the following code and got the expected output:
class SampleClass
{
public function getValue()
{
return 4;
}
}
$sc = new SampleClass();
SampleFunction($sc);
function SampleFunction(&$refClass)
{
echo $refClass->getValue();
}
Output: 4
If you provide more details of your actual code we might be able to determine the problem.
I can't see anything wrong with your code
using &$refClass is however is not recommended and I guess willbe removed from future iteration of PHP version
but here is an example
class objects are passed as reference I suppose so no need of '&'
http://ideone.com/GbmUy
Why is the function argument a reference? Probably shouldn't be.
Other than that, there's nothing wrong with you posted, so the error is likely within SampleClass.
Others have answered pretty well, but this is a silly little example to show you how to modify the class (either by calling a property setter, or setting public properties directly)
class foo {
private $member1;
public $member2;
public function __construct($member1,$member2) {
$this->member1=$member1;
$this->member2=$member2;
}
public function SetMember1($value) {
$this->member1 = $value;
}
public function GetMember1() {
return $this->member1;
}
}
function SetMembers(foo $obj, $member1, $member2) {
// Call a setter
$obj->SetMember1($member1);
// Set a member variable directly
$obj->member2 = $member2;
}
$obj = new foo('default member 1', 'default member 2');
echo "member1 (before): {$obj->GetMember1()}\n";
echo "member2 (before): {$obj->member2}\n";
// Change values
SetMembers($obj, 'new member1', 'new member2');
echo "member1 (after): {$obj->GetMember1()}\n";
echo "member2 (after): {$obj->member2}\n";
This will output:
member1 (before): default member 1
member2 (before): default member 2
member1 (after): new member1
member2 (after): new member2
If I call $object->showSomething() and the showSomething method doesn't exist I get a fata error. That's OK.
But I have a show() method that takes a argument. Can I somehow tell PHP to call show('Something'); when it encounters $object->showSomething() ?
Try something like this:
<?php
class Foo {
public function show($stuff, $extra = '') {
echo $stuff, $extra;
}
public function __call($method, $args) {
if (preg_match('/^show(.+)$/i', $method, $matches)) {
list(, $stuff) = $matches;
array_unshift($args, $stuff);
return call_user_func_array(array($this, 'show'), $args);
}
else {
trigger_error('Unknown function '.__CLASS__.':'.$method, E_USER_ERROR);
}
}
}
$test = new Foo;
$test->showStuff();
$test->showMoreStuff(' and me too');
$test->showEvenMoreStuff();
$test->thisDoesNothing();
Output:
StuffMoreStuff and me tooEvenMoreStuff
Not necessarily just the show.... methods, but any method, yes, use __call. Check for the method asked in the function itself.
You can use the function method_exists(). Example:
class X {
public function bar(){
echo "OK";
}
}
$x = new X();
if(method_exists($x, 'bar'))
echo 'call bar()';
else
echo 'call other func';
I have a class 'abc', with several functions inside it:
'abc_function1'
'abc_function2'
'abc_function3'
'abc_function4'
'abc_function5'
I would like to call a function of the class 'abc' according to a parameter that I enter, a string containing 'function1' or 'function 4' for example, to refer to the corresponding function of the class.
I hope I've made myself clear ;)
Thanks a lot for your help
Not exactly sure why but this has a certain code smell in my opinion. But anyway...
Method a): Implement the "magic" method __call($name, $params).
<?php
class Foo {
public function abc_function1() {
echo "function #1";
}
public function abc_function2() {
echo "function #2";
}
public function abc_function3() {
echo "function #3";
}
public function __call($name, $params) {
$fqn = 'abc_'.$name;
if ( method_exists($this, $fqn) ) {
call_user_func_array( array($this, $fqn), $params);
}
}
}
$f = new Foo;
$f->function2();
Method b): Same idea, just without the automagical mapping.
<?php
class Foo {
public function abc_function1() {
echo "function #1";
}
public function abc_function2() {
echo "function #2";
}
public function abc_function3() {
echo "function #3";
}
public function doSomething($x, $y, $z) {
$fqn = 'abc_'.$x;
if ( method_exists($this, $fqn) ) {
call_user_func_array( array($this, $fqn), array($y, $z));
}
}
}
$f = new Foo;
$f->doSomething('function2', 1, 2);
Method c) If you know the number of parameter you can also use
$this->$fqn($,y, $z)
instead of
call_user_func_array( (array($this, $fqn), array($y, $z) );
see also: http://docs.php.net/call_user_func_array and http://docs.php.net/functions.variable-functions
$class_instance = new class();
call_user_func(
array( $class_instance, $your_string_containing_the_fx_name ),
$the_parameters_you_want_to_pass
);
You can use the variable functions feature of PHP:
function call_function( $string ) {
$var = 'abc_' . $string;
$retval = $var(); // this will call function named 'abc_'
// plus the contents of $string
return $retval;
}