Is there any way in PHP to tell if a function is being run from inside or outside a particular class of object?
function getToDaChoppa() {
if( "we're inside the Choppa object" ) {
$foo = "We're inside";
} else {
$foo = "We're outside";
}
echo $foo;
}
class Choppa() {
public function getStatus() {
getToDaChoppa();
}
}
Running:
getToDaChoppa();
( new Choppa )->getStatus();
should echo:
We're Outside
We're Inside
A function on it's own doesn't know, if it's called from an class or not and that for good reasons. If the function behaves different, that would lead to very unmaintainable code and hard debugging, etc.
If you need the calling function and maybe ask, if this function belongs to an class/get the instance, the only way to do this is debug_backtrace. But in general you really only should do this, for debug code (as the name tells you).
Normally you would just have two functions for each case, or pass an parameter, which stores the desired information.
You could always pass an instance of the class through on top of a default value, then evaluate on the return of a get_class().
function getToDaChoppa($that = false) {
$class = $that ? get_class($that) : '';
if($class == "Choppa") {
$foo = "We're inside";
} else {
$foo = "We're outside";
}
echo $foo;
}
class Choppa {
public function getStatus() {
getToDaChoppa($this);
}
}
getToDaChoppa(); // Would return "We're outside"
( new Choppa )->getStatus(); // Would return "We're inside"
See https://ideone.com/WWg1Hl for a working example.
You might use debug_backtrace(), go back one hop, and check if that was made from inside a class. I'm not sure I'd do this in production though...
function getToDaChoppa() {
$bt = debug_backtrace();
if (isset($bt[1]) && array_key_exists('class', $bt[1])) {
echo "called from class\n";
} else {
echo "called directly\n";
}
}
Clarification: if you want it to trigger only for one specific class:
function getToDaChoppa() {
$bt = debug_backtrace();
if (
isset($bt[1]) &&
array_key_exists('class', $bt[1]) &&
$bt[1]['class'] === 'Choppa'
) {
echo "called from class Choppa\n";
} else {
echo "called otherwise\n";
}
}
Related
I have following php code in basic.php. How can I determine if the method row() was called? When I write next <?php $basic->row(); ?> it shows something like this - the method was defined!
Example
$basic->container(); // container was called
$basic->container(); // when called again, i need show some warning - CONTAINER CAN BE PUT ONLY ONCE and using exit() for example
This is the solution what i need
public function container(){
static $container = false;
if ( $container ){ return; } else { print '<div class="container">'; } $container = true;
}
If you want to know if an object has a method or not before calling it, you can use method_exists.
if(method_exists($basic, 'row')) {
$basic->row();
}
Use the echo construct inside the row function like this:
// your code
function row(){
echo "Function called!";
....
}
This will print the text "Function called!" everytime you call the function.
I just add it as an answer ... try smthg like this:
function row(){
if($wascalled === true) {
echo "The function was called";
}
//your Code here
$wascalled = true;
}
So, the first time you call the function, nothing happens, if you call it more, the message will appear. It looks ugly and i dont see much sense in it, but it seems to work.
I did not understand if you mean really a call or if the method is defined.
As #Prasanth said, if you mean if the method is defined - method_exists will be a solution.
Otherwise, you can check my answer here: Cahining pattern
It's related to your problem, as you need a generic way to register a method been called before.
You, ofcourse, can write down
public $_row = false;
public function row() {
$this->_row = true;
// some stuff
}
and later:
if (!$basic->_row) {
$basic->row();
}
You just need a property where you will set a value, which corresponds to your script later. I.e. here the default value is false - it means the method hasn't been called yet. Once method is called, it changes it to true. You are testing if the value is default (false) then call.
You may not change the value to true, but to the string you wanted. E.g. $this->_row = 'the method was defined!' Or set to true and print the string, if $this->_row == true.
Reference
bool function_exists ( string $function_name )
Parameters The $function_name, as a string.
Returns TRUE if function_name exists and is a function, FALSE otherwise.
Note:
This function will return FALSE for constructs, such as include_once and echo.
<?php
if (function_exists('function_name')) {
echo "IMAP functions are available.<br />\n";
} else {
echo "IMAP functions are not available.<br />\n";
}
?>
Take this as an example
<?php
if (function_exists('foo')) {
print "foo defined\\n";
} else {
print "foo not defined\\n";
}
function foo() {}
if (function_exists('bar')) {
print "bar defined\\n";
} else {
print "defining bar\\n";
function bar() {}
}
print "calling bar\\n";
bar(); // ok to call function conditionally defined earlier
print "calling baz\\n";
baz(); // ok to call function unconditionally defined later
function baz() {}
qux(); // NOT ok to call function conditionally defined later
if (!function_exists('qux')) {
function qux() {}
}
?>
Prints:
foo defined
defining bar
calling bar
calling baz
PHP Fatal error: Call to undefined function qux()
Alternative method
You can use magic method __call.
class Basic{
function row(){
print ' Call method '.__METHOD__.'<br/>';
}
function __call($method,$params){
if (method_exists($this, $method)) {
call_user_func_array(array($this, $method), $params);
}else{
print 'Class '.__CLASS__.' hasn`t method "'.$method.'"<br/>';
}
}
}
$basic = new Basic();
$basic->row();
$basic->fetch();
// output
Call method Basic::row
Class Basic hasn`t method "fetch"
Same function name in different isolated classes is not allowed?
What am I doing wrong?
I reduced my real code to the minimum required to make some test.
Here it is:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
class confFunctions {
function getConf() {
function doWork() {
echo "I am from confFunctions!<br />";
}
doWork();
}
}
class thePage {
function loadPage() {
function doWork() {
echo "I am from thePage!<br />";
}
doWork();
}
}
// Start check.
echo "Checking...<br />";
$conf = new confFunctions();
$conf->getConf();
$page = new thePage();
$page->loadPage();
?>
The output is:
Checking...
I am from confFunctions!
Fatal error: Cannot redeclare doWork() (previously declared in /var/www/Test2/index.php:11) in /var/www/Test2/index.php on line 23
Renaming one of the shared-name functions makes all working well. That is, changing doWork to doWork1 in the second class, like this:
class thePage {
function loadPage() {
function doWork1() {
echo "I am from thePage!<br />";
}
doWork1();
}
}
gives correct results:
Checking...
I am from confFunctions!
I am from thePage!
Should not what is inside a class be visible only to that class, if not declared public?
By declaring a function in a function, you are actually declaring the second function into the global scope.
If you want your functions to be limited to the class scope, don't declare a function in another function, but rather declare them under each other.
Consider this code that declares a function in another function (in a class):
<?php
class MyFunctions {
function load() {
function doWork() {
echo "I am doing my work from global scope";
}
}
}
$mf = new MyFunctions();
$mf->load();
// $mf->doWork(); <-- won't work here
doWork(); // <-- this will work!
?>
Now consider this code that declares a function under another function (in a class).
<?php
class MyFunctions {
function load() {
//...
}
function doWork() {
echo "I am doing my work from class scope";
}
}
$mf = new MyFunctions();
// $mf->load(); <-- not really important anymore
$mf->doWork(); // <-- this will work now
// doWork(); <-- won't work here anymore
?>
Function scope is always namespace wide when declaring a named function.
You'll need to assign it to a variable to constrain it to a specific scope ($doWork = function() { }).
You seem to be going down an odd path though. Perhaps you should just use a private method?
Full example just to make it clear:
class confFunctions {
function getConf() {
$doWork = function() {
echo "I am from confFunctions!<br />";
};
$doWork();
}
}
class thePage {
function loadPage() {
$doWork = function() {
echo "I am from thePage!<br />";
};
$doWork();
}
}
I dont think you meant to nest the functions ? and your calling them from the global scope.
something like this is likely what you meant
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
class confFunctions {
function getConf() {
$this->doWork();
}
function doWork() {
echo "I am from confFunctions!<br />";
}
}
class thePage {
function loadPage() {
$this->doWork();
}
function doWork() {
echo "I am from thePage!<br />";
}
}
// Start check.
echo "Checking...<br />";
$conf = new confFunctions();
$conf->getConf();
$page = new thePage();
$page->loadPage();
?>
First guess would be that somehow you aren't properly closing your class from the first example. Different classes are definitely allowed to have the same function names, so there's something else going on in your code here that's not being shown through the psuedo-code you're posting.
UPDATE:
As NL-X said, by posting the function inside of a class function it then creates it in global scope. Thank you for updating your pseudo-code with actual examples.
In PHP, I'm trying to reference a method defined in an object's parent class, from a method inherited from the object's parent class. Here's the code:
class base_class {
function do_something() {
print "base_class::do_something()\n";
}
function inherit_this() {
parent::do_something();
}
}
class middle_class extends base_class {
function do_something() {
print "middle_class::do_something()\n";
}
}
class top_class extends middle_class {
function do_something() {
print "top_class::do_something()\n";
$this->inherit_this();
}
}
$obj = new top_class;
$obj->do_something();
The problem is that parent::do_something() in inherit_this() tries to find the parent class of base_class, not the parent of the object's actual class, and the example above throws an error. Is there something I can write instead of parent::do_something() that would call middle_class::do_something(), and that would still work even in classes that extend (say) top_class?
To get it work you can modify your base_class like this:
class base_class {
function do_something() {
print "base_class::do_something()\n";
}
function inherit_this() {
$this->do_something();
}
}
Then your top_clas will call inherit_this() of your base class, but there will be a recursion: do_something() of top_class calls $this->inherit_this(), and in base_class you call again $this->do_something() (in your base class $this will reference to your top_class). Because of that, you will call inherit_this() over and over again.
You should rename the methods to prevent that.
Update
If you want that base_class inherit_this() prints "base_class::do_something" you could modify your base_class like this:
class base_class {
function do_something() {
print "base_class::do_something()\n";
}
function inherit_this() {
base_class::do_something();
}
}
In this case you make a static call to the base_class method do_something(). The output is top_class::do_something() base_class::do_something()
Update 2
Regarding to your comment you can modify your base_class like this:
class base_class {
function do_something() {
print "base_class::do_something()\n";
}
function inherit_this() {
$par = get_parent_class($this);
$par::do_something();
}
}
You get the parrent class of $this and then call the method. Output will be: top_class::do_something() middle_class::do_something()
I'll start by saying "Thank you" to grrbrr404. He gave me some ideas and got me started in the right direction.
The solution I finally settled on was the following:
function inherit_this() {
$bt = debug_backtrace();
call_user_func(array($this, get_parent_class($bt[1]['class']) . '::do_something'));
}
It's not pretty (I particularly hate calling debug_backtrace() for this), but it keeps the object context set to $this, and handles the case where the method is called from a method somewhere in the middle of the object hierarchy.
For those who found my example confusing and/or wanted to know "Why would you want to do this?" I apologize, and provide the following additional example, which is hopefully more illustrative and closer to the original problem. It is considerably longer, but hopefully shows why I care about keeping $this set properly, and also shows why I can't hard-code any particular class name or use $this->method(). Avoiding infinite loops is always a priority with me. :-)
class class1_required_type { }
class class2_required_type { }
class class3_required_type { }
class class4_required_type { }
class class1 {
protected $data = array();
protected function checkType($name, $value, $requiredType) {
print "In class1::checkType()\n";
if (get_class($value) === $requiredType) {
$backtrace = debug_backtrace();
call_user_func(array($this, get_parent_class($backtrace[1]['class']) . "::mySet"), $name, $value);
} else {
throw new Exception(get_class($this) . "::mySet('" . $name . "') requires an object of type '" . $requiredType . "', but got '" . get_class($value) . "'");
}
}
function mySet($name, $value) {
print "In class1::mySet()\n";
if ($name === 'class1_field') {
$this->checkType($name, $value, 'class1_required_type');
} else {
$this->data[$name] = $value;
}
}
function dump() {
foreach ($this->data as $key => $value) {
print "$key: " . get_class($value) . "\n";
}
}
}
class class2 extends class1 {
function mySet($name, $value) {
print "In class2::mySet()\n";
if ($name === 'class2_field') {
$this->checkType($name, $value, 'class2_required_type');
} else {
parent::mySet($name, $value);
}
}
}
class class3 extends class2 {
function mySet($name, $value) {
print "In class3::mySet()\n";
if ($name === 'class3_field') {
$this->checkType($name, $value, 'class3_required_type');
} else {
parent::mySet($name, $value);
}
}
}
class class4 extends class3 {
function mySet($name, $value) {
print "In class4::mySet()\n";
if ($name === 'class4_field') {
$this->checkType($name, $value, 'class4_required_type');
} else {
parent::mySet($name, $value);
}
}
}
$obj = new class4;
$obj->mySet('class3_field', new class3_required_type);
$obj->dump();
I'm trying to avoid duplication of the "checkType()" function, yet still provide correct behavior even when the hierarchy gets arbitrarily large.
More elegant solutions are, of course, most welcome.
Im not quite sure I understands why you want to do like this. But I guess you cannot do it. I understand that you will be able to make a middle_class2 and be able inherit from that, and then it would be middle_class2 instead of middle_class's dosomething you call?!
So I guess you'll need to create the
function inherit_this() {
parent::do_something();
}
in the middle_class.
I thought about a get_class($this)::parent::do_something().. but that didn't work.
Just to be sure.. You want to call middle_class::do_something() right??
class base_class {
function do_something() {
print "base_class::do_something()\n";
}
function inherit_this() {
//parent::do_something();
$class = get_called_class();
$class::do_something();
}
}
I've got an Abstract PHP superclass, which contains code that needs to know which subclass its running under.
class Foo {
static function _get_class_name() {
return get_called_class();
//works in PHP 5.3.*, but not in PHP 5.2.*
}
static function other_code() {
//needs to know
echo self::_get_class_name();
}
}
class Bar extends Foo {
}
class FooBar extends Foo {
}
Bar::other_code(); // i need 'Bar'
FooBar::other_code(); // i need 'FooBar'
This would work if I called the function get_called_class() -- however, this code is going to be run in PHP version 5.2.*, so that function is not available.
There's some custom PHP implementations of get_called_class() out there, but they all rely on going thru the debug_backtrack(), parsing a file name & line number, and running a regex (as the coder is not aware that PHP 5.2 has reflection) to find the class name. This code needs to be able to be run with php, ie. not only from a .php file. (It needs to work from a php -a shell, or an eval() statement.)
Ideally, a solution would work without requiring any code to be added to the subclasses… The only potential solution I can see though is adding the following code to each subclass, which is obviously a disgusting hack:
class FooBar extends Foo {
static function _get_class_name() {
return 'FooBar';
}
}
EDIT: Wait, this doesn't even seem to work. It would've been my last resort. Can anybody think of something similar to this solution that'd get me the required functionality. Ie., I'm willing to accept a solution that requires me to add one function or variable to each subclass telling it what its class name is. Unfortunately, it seems that calling self::_get_class_name() from the superclass calls the parent class' implementation, even if the subclass has overridden it.
In reality it is often helpful to know the actual called (sub)class when executing a superclass method, and I disagree that there's anything wrong with wanting to solve this problem.
Example, my objects need to know the class name, but what they do with that information is always the same and could be extracted into a superclass method IF I was able to get the called class name. Even the PHP team thought this was useful enough to include in php 5.3.
The correct and un-preachy answer, as far as I can tell, is that prior to 5.3, you have to either do something heinous (e.g. backtrace,) or just include duplicate code in each of the subclasses.
Working solution:
function getCalledClass(){
$arr = array();
$arrTraces = debug_backtrace();
foreach ($arrTraces as $arrTrace){
if(!array_key_exists("class", $arrTrace)) continue;
if(count($arr)==0) $arr[] = $arrTrace['class'];
else if(get_parent_class($arrTrace['class'])==end($arr)) $arr[] = $arrTrace['class'];
}
return end($arr);
}
This is not possible.
The concept of "called class" was introduced in PHP 5.3. This information was not tracked in previous versions.
As an ugly work-around, you could possibly use debug_backtrace to look into the call stack, but it's not equivalent. For instance, in PHP 5.3, using ClassName::method() doesn't forward the static call; you have no way to tell this with debug_backtrace. Also, debug_backtrace is relatively slow.
The PHP/5.2 alternative to late static binding that keeps duplicate code to the minimum while avoiding weird hacks would be to create one-liners on child classes that pass the class name as argument:
abstract class Transaction{
public $id;
public function __construct($id){
$this->id = $id;
}
protected static function getInstanceHelper($class_name, $id){
return new $class_name($id);
}
}
class Payment extends Transaction{
public static function getInstance($id){
return parent::getInstanceHelper(__CLASS__, $id);
}
}
class Refund extends Transaction{
public static function getInstance($id){
return parent::getInstanceHelper(__CLASS__, $id);
}
}
var_dump( Payment::getInstance(1), Refund::getInstance(2) );
object(Payment)#1 (1) {
["id"]=>
int(1)
}
object(Refund)#2 (1) {
["id"]=>
int(2)
}
The solution is:
get_class($this);
However, I don't know if this sentence works in static functions. Give it a try and tell me your feedback.
This hack includes the heinous use of debug_backtrace... not pretty, but it does the job:
<?php
function callerName($functionName=null)
{
$btArray = debug_backtrace();
$btIndex = count($btArray) - 1;
while($btIndex > -1)
{
if(!isset($btArray[$btIndex]['file']))
{
$btIndex--;
if(isset($matches[1]))
{
if(class_exists($matches[1]))
{
return $matches[1];
}
else
{
continue;
}
}
else
{
continue;
}
}
else
{
$lines = file($btArray[$btIndex]['file']);
$callerLine = $lines[$btArray[$btIndex]['line']-1];
if(!isset($functionName))
{
preg_match('/([a-zA-Z\_]+)::/',
$callerLine,
$matches);
}
else
{
preg_match('/([a-zA-Z\_]+)::'.$functionName.'/',
$callerLine,
$matches);
}
$btIndex--;
if(isset($matches[1]))
{
if(class_exists($matches[1]))
{
return $matches[1];
}
else
{
continue;
}
}
else
{
continue;
}
}
}
return $matches[1];
}
I have asked a question like this before, because I wanted a parent to have a factory method that was something like this
public static function factory() {
return new __CLASS__;
}
But it always returned the parent class, not the inherited one.
I was told that it is not possible without late static binding. It was introduced in PHP 5.3. You can read the documentation.
This function does the same job but works with instances too:
if (!function_exists('get_called_class')) {
function get_called_class() {
$bt = debug_backtrace();
/*
echo '<br><br>';
echo '<pre>';
print_r($bt);
echo '</pre>';
*/
if (self::$fl == $bt[1]['file'] . $bt[1]['line']) {
self::$i++;
} else {
self::$i = 0;
self::$fl = $bt[1]['file'] . $bt[1]['line'];
}
if ($bt[1]['type'] == '::') {
$lines = file($bt[1]['file']);
preg_match_all('/([a-zA-Z0-9\_]+)::' . $bt[1]['function'] . '/', $lines[$bt[1]['line'] - 1], $matches);
$result = $matches[1][self::$i];
} else if ($bt[1]['type'] == '->') {
$result = get_class($bt[1]['object']);
}
return $result;
}
}
<?php
class Foo {
private static $instance;
static function _get_class_name() {
return self::myNameIs();
}
static function other_code() {
//needs to know
echo self::_get_class_name();
}
}
class Bar extends Foo {
public static function myNameIs() {
self::$instance = new Bar();
return get_class(self::$instance);
}
}
class FooBar extends Foo {
public static function myNameIs() {
self::$instance = new FooBar();
return get_class(self::$instance);
}
}
Bar::other_code(); // i need 'Bar'
FooBar::other_code(); // i need 'FooBar'
I've been wondering whether it is possible or not to pass a function as a parameter in PHP. I want something similar to when you're programming the following code in JavaScript:
object.exampleMethod(function(){
// some stuff to execute
});
What I want is to execute that function somewhere in exampleMethod. Is that possible in PHP?
It's possible if you are using PHP 5.3.0 or higher.
See Anonymous Functions in the manual.
In your case, you would define exampleMethod like this:
function exampleMethod($anonFunc) {
//execute anonymous function
$anonFunc();
}
Just to add to the others, you can pass a function name:
function someFunc($a)
{
echo $a;
}
function callFunc($name)
{
$name('funky!');
}
callFunc('someFunc');
This will work in PHP4.
Valid: (PHP 4 >= 4.0.1, PHP 5, PHP 7)
You can also use create_function to create a function as a variable and pass it around. Though, I like the feeling of anonymous functions better. Go zombat.
Update 09 - Jan - 2022
Warning
This function has been DEPRECATED as of PHP 7.2.0, and REMOVED as of PHP 8.0.0. Relying on this function is highly discouraged.
Just code it like this:
function example($anon) {
$anon();
}
example(function(){
// some codes here
});
it would be great if you could invent something like this (inspired by Laravel Illuminate):
Object::method("param_1", function($param){
$param->something();
});
PHP VERSION >= 5.3.0
Example 1: basic
function test($test_param, $my_function) {
return $my_function($test_param);
}
test("param", function($param) {
echo $param;
}); //will echo "param"
Example 2: std object
$obj = new stdClass();
$obj->test = function ($test_param, $my_function) {
return $my_function($test_param);
};
$test = $obj->test;
$test("param", function($param) {
echo $param;
});
Example 3: non static class call
class obj{
public function test($test_param, $my_function) {
return $my_function($test_param);
}
}
$obj = new obj();
$obj->test("param", function($param) {
echo $param;
});
Example 4: static class call
class obj {
public static function test($test_param, $my_function) {
return $my_function($test_param);
}
}
obj::test("param", function($param) {
echo $param;
});
According to #zombat's answer, it's better to validate the Anonymous Functions first:
function exampleMethod($anonFunc) {
//execute anonymous function
if (is_callable($anonFunc)) {
$anonFunc();
}
}
Or validate argument type since PHP 5.4.0:
function exampleMethod(callable $anonFunc) {}
Tested for PHP 5.3
As i see here, Anonymous Function could help you:
http://php.net/manual/en/functions.anonymous.php
What you'll probably need and it's not said before it's how to pass a function without wrapping it inside a on-the-fly-created function.
As you'll see later, you'll need to pass the function's name written in a string as a parameter, check its "callability" and then call it.
The function to do check:
if( is_callable( $string_function_name ) ){
/*perform the call*/
}
Then, to call it, use this piece of code (if you need parameters also, put them on an array), seen at : http://php.net/manual/en/function.call-user-func.php
call_user_func_array( "string_holding_the_name_of_your_function", $arrayOfParameters );
as it follows (in a similar, parameterless, way):
function funToBeCalled(){
print("----------------------i'm here");
}
function wrapCaller($fun){
if( is_callable($fun)){
print("called");
call_user_func($fun);
}else{
print($fun." not called");
}
}
wrapCaller("funToBeCalled");
wrapCaller("cannot call me");
Here's a class explaining how to do something similar :
<?php
class HolderValuesOrFunctionsAsString{
private $functions = array();
private $vars = array();
function __set($name,$data){
if(is_callable($data))
$this->functions[$name] = $data;
else
$this->vars[$name] = $data;
}
function __get($name){
$t = $this->vars[$name];
if(isset($t))
return $t;
else{
$t = $this->$functions[$name];
if( isset($t))
return $t;
}
}
function __call($method,$args=null){
$fun = $this->functions[$method];
if(isset($fun)){
call_user_func_array($fun,$args);
} else {
// error out
print("ERROR: Funciton not found: ". $method);
}
}
}
?>
and an example of usage
<?php
/*create a sample function*/
function sayHello($some = "all"){
?>
<br>hello to <?=$some?><br>
<?php
}
$obj = new HolderValuesOrFunctionsAsString;
/*do the assignement*/
$obj->justPrintSomething = 'sayHello'; /*note that the given
"sayHello" it's a string ! */
/*now call it*/
$obj->justPrintSomething(); /*will print: "hello to all" and
a break-line, for html purpose*/
/*if the string assigned is not denoting a defined method
, it's treat as a simple value*/
$obj->justPrintSomething = 'thisFunctionJustNotExistsLOL';
echo $obj->justPrintSomething; /*what do you expect to print?
just that string*/
/*N.B.: "justPrintSomething" is treated as a variable now!
as the __set 's override specify"*/
/*after the assignement, the what is the function's destiny assigned before ? It still works, because it's held on a different array*/
$obj->justPrintSomething("Jack Sparrow");
/*You can use that "variable", ie "justPrintSomething", in both ways !! so you can call "justPrintSomething" passing itself as a parameter*/
$obj->justPrintSomething( $obj->justPrintSomething );
/*prints: "hello to thisFunctionJustNotExistsLOL" and a break-line*/
/*in fact, "justPrintSomething" it's a name used to identify both
a value (into the dictionary of values) or a function-name
(into the dictionary of functions)*/
?>
Simple example using a class :
class test {
public function works($other_parameter, $function_as_parameter)
{
return $function_as_parameter($other_parameter) ;
}
}
$obj = new test() ;
echo $obj->works('working well',function($other_parameter){
return $other_parameter;
});
Here is a simple procedural example of how you could implement validation of multiple data items using separate functions for each data item validation, passed as an array of functions argument to a master validations function, with the data to be validated (the arguments to the functions) passes as the other array argument to the master validation function. Useful for writing generic code to validate form data.
<?php
function valX($value) {
echo "<p>Validating $value == 5</p>";
if ($value == 5) {
return true;
} else {
return false;
}
}
function valY($value) {
echo "<p>Validating $value == 6</p>";
if ($value == 6) {
return true;
} else {
return false;
}
}
function validate($values, $functions) {
for ($i = 0; $i < count($values); $i++) {
if ($functions[$i]($values[$i])) {
echo "<p>$values[$i] passes validation</p>";
} else {
echo "<p>$values[$i] fails validation</p>";
}
}
}
$values = [5, 9];
$functions = ['valX', 'valY'];
validate($values, $functions);
?>