Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP function in a function

Tags:

function

php

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")
like image 438
fteinz Avatar asked May 02 '26 20:05

fteinz


1 Answers

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";
like image 186
Justin ᚅᚔᚈᚄᚒᚔ Avatar answered May 05 '26 10:05

Justin ᚅᚔᚈᚄᚒᚔ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!