Robert
Robert

Reputation: 11

PHP FILTER_CALLBACK in OOP Class

Hi I've been playing around with phps filter class getting and have come across a snag with the filter_callback filter.

the following rough bit of code works but shows an error every time

Warning: filter_var() [function.filter-var]: First argument is expected to be a valid callback in /Users/Rob/sites/test_val.php on line 12

class test

{

public function callback($string)
{

$var = filter_var($string, FILTER_CALLBACK, array('options' => $this->foo($string)));

} 

public function foo($string){

echo $string;


}

}


$test = new test();

$string = 'test';

$tested = $test->callback($string);

am i calling the function correctly or is there a different way?

Upvotes: 1

Views: 3296

Answers (3)

PFinal南丞
PFinal南丞

Reputation: 1

echo filter_var('wo9w9w9', FILTER_CALLBACK, array('options' => array(new MyFilter(), 'filter1'))) . PHP_EOL;  

options You can directly transfer object instance, like $this or new self ,

Upvotes: 0

Hirdesh Vishwdewa
Hirdesh Vishwdewa

Reputation: 2362

This code works for me :)

 <?php
    class myClass {
     public function myFunc($var){
       return filter_var($var, FILTER_CALLBACK, array('options'=> 'self::myCallback'));
     }
     public function myCallback(){
      return true;
     }
    }
$obj = new myClass();

var_dump($obj->myFunc("[email protected]"));
//output:- bool(true)

?>

Upvotes: 3

alex
alex

Reputation: 490283

$this->foo($string)

...should be...

array($this, 'foo')

When using a method as a callback, you need to provide the reference in this manner.

Documentation.

Upvotes: 9

Related Questions