PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Callback

This filter allows you to use own methods in conjunction with Zend_Filter. You don't have to create a new filter when you already have a method which does the job.

Supported options for Zend_Filter_Callback

The following options are supported for Zend_Filter_Callback:

  • callback: This sets the callback which should be used.

  • options: This property sets the options which are used when the callback is processed.

Basic usage

The usage of this filter is quite simple. Let's expect we want to create a filter which reverses a string.

<?php
$filter 
= new Zend_Filter_Callback('strrev');

print 
$filter->filter('Hello!');
// returns "!olleH"

As you can see it's really simple to use a callback to define a own filter. It is also possible to use a method, which is defined within a class, by giving an array as callback.

<?php
// Our classdefinition
class MyClass
{
    public function 
Reverse($param);
}

// The filter definition
$filter = new Zend_Filter_Callback(array('MyClass''Reverse'));
print 
$filter->filter('Hello!');

To get the actual set callback use getCallback() and to set another callback use setCallback().

Possible exceptions

You should note that defining a callback method which can not be called will raise an exception.

Default parameters within a callback

It is also possible to define default parameters, which are given to the called method as array when the filter is executed. This array will be concatenated with the value which will be filtered.

<?php
$filter 
= new Zend_Filter_Callback(
    array(
        
'callback' => 'MyMethod',
        
'options'  => array('key' => 'param1''key2' => 'param2')
    )
);
$filter->filter(array('value' => 'Hello'));

When you would call the above method definition manually it would look like this:

<?php
$value 
MyMethod('Hello''param1''param2');

Zend Framework