fteinz
fteinz

Reputation: 1095

PHP function in a function

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")

Upvotes: 2

Views: 217

Answers (5)

ghoti
ghoti

Reputation: 46896

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:~$

Upvotes: 2

rbawaskar
rbawaskar

Reputation: 1045

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;
    }
}

Upvotes: 1

afuzzyllama
afuzzyllama

Reputation: 6548

If you are doing this for a class, consider using PHP's magic methods __get() and __set().

Upvotes: 2

Ofir Baruch
Ofir Baruch

Reputation: 10346

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");

Upvotes: 2

Justin ᚅᚔᚈᚄᚒᚔ
Justin ᚅᚔᚈᚄᚒᚔ

Reputation: 15359

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";

Upvotes: 3

Related Questions