How to use PHP is_callable function

Source: Internet
Author: User


PHP's is_callable is used to detect whether a function or a class method can be executed, in official documents, to detect whether the parameter is a legitimate callable structure, as shown in the code.

Class A
{public
function __construct () {
echo ' Class: '. Get_called_class ();
The public
function cc () {
$a = 3;
return $a;
}
}
$a = new A;
$test = is_callable (Array (' A ', ' cc '));
Var_dump ($test); exit;
Printed result:
class:a
Boolean True

Official Example:

function someFunction ()

{

}

$functionVariable = ' someFunction ';

Var_dump (Is_callable ($functionVariable, False, $callable _name));  BOOL (TRUE)

echo $callable _name, "\ n"; SomeFunction////

Array containing a method

//

class SomeClass {

functi On SomeMethod ()

{

}

}

$anObject = new SomeClass ();

$methodVariable = Array ($anObject, ' SomeMethod ');

Var_dump (Is_callable ($methodVariable, True, $callable _name));  BOOL (TRUE)

echo $callable _name, "\ n"; Someclass::somemethod

The official example is a detection function, a method for detecting classes, and a more specific usage.

Example

The demo code is as follows:

<?php

class Test {

static function A () {return

"Test";

}

}

Class ABC {public

function A ($Object, $funcName) {

if (!is_callable ($Object, $funcName)) {//here Array ($  Object, $funcname), equivalent to $object:: $funcname invoke $object's $funcname method

echo ("Error");

}else {

echo ("OK");

}

}

$abc =new ABC ();

$ABC->a ("Test", "AA"), there is no AA method under//test class, output error

$abc->a ("Test", "a"),//test class has a method, output OK

?>

OK, the use of this function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.