How to call a child method from filter_var callback in parent

88 Views Asked by At

I have a child class that holds a bunch of private properties. The parent class has the __SET & __GET methods.

The parent __SET method has filter_var($var, FILTER_CALLBACK, ['options' => 'childMethod'); but it always fails with the error filter_var(): First argument is expected to be a valid callback

See example code below, you can copy and paste it into http://phpfiddle.org/lite/

For "childMethod" I have tried using:

  • $this->childMethod()
  • $this->childMethod
  • this->childMethod
  • this->childMethod()
  • childMethod()
  • childMethod

all error

<?php
abstract class a {
    public function callChild() {
        $var = $this->iAmChild();
        echo $var."<br />";
        echo filter_var($var, FILTER_CALLBACK, ["options" => 'this->callback'])."<br />";
        echo $this->callback($var)."<br />";
    }

    // abstract function callback();
}

class b extends a {
    public function iAmChild() {
        return "I am the child function";
    }
    public function callback($value) {
        $value = strtoupper($value);
        return $value;
    }
}

$child = new b();

$child->callChild();




function convertSpace($string)
  {
  return str_replace(" ", "_", $string);
  }

$string = "Peter is a great guy!";

echo filter_var($string, FILTER_CALLBACK,["options"=>"convertSpace"]);
?>

Is it possible?

Each child class is a representation of a database table, so I want to filter and control the "setting" of the properties. Each child class has the list of properties, and an array or arrays that provide the type of FILTER_* to use for each property. this works for all of them except the FILTER_CALLBACK.

How can I pass the child method as a callback function to filter_var?

1

There are 1 best solutions below

0
On BEST ANSWER

The answer as noted in the comments was to change the 6th line of code from
echo filter_var($var, FILTER_CALLBACK, ["options" => 'this->callback'])."<br />";
to
echo filter_var($var, FILTER_CALLBACK, ["options" => [$this, 'callback'])."<br />";