Home > php教程 > php手册 > PHP函数常用用法小结

PHP函数常用用法小结

WBOY
Release: 2016-06-06 20:32:39
Original
1040 people have browsed it

由于PHP是一种解释型语言,所以函数编写和调用很是方便。总结一下魔术函数、嵌套函数、匿名函数、函数调用方式和函数参数使用等。

下面是一个简单的例子

function __autoload($class_name)

{

require_once $class_name . '.class.php';

}

另外附赠几个常量和函数:

$func=create_function('$a,$b', '

if ($a == $b)

{

return 0;

}

return ($a

');

$func=function($a,$b)

{

if ($a == $b)

{

return 0;

}

return ($a

}

function foo($arg1)

{

$var=3;

$inner=function($innerArg) use($arg1,$var)

{

return $innerArg+$arg1/$var;

};

echo $inner(5);

}

嵌套函数可以在父函数体里面定义函数,如:

function outer()

{

$out_var=1;

function inner()

{

echo "call inner\n";

}

//echo "call outer\n";

}

outer();

$debug=false;

if($debug===true)

{

function foo()

{

echo "foo";

}

}

foo();

函数名可以是变量名。

function foo()

{

echo "call foo";

}

$func='foo';

$func();

调用类的方法则传入一个数组作为参数,此数组第一个元素是实例或类名,第二个元素是方法名:

class myclass

{

public $age=21;

function echo_age()

{

echo $this->age;

}

static function s_echo_age()

{

echo 22;

}

function i_echo_age()

{

echo 23;

}

}

$c=new myclass;

$classname = "myclass";

call_user_func(array($c, 'echo_age'));

echo "\n";

call_user_func(array($classname, 'i_echo_age'));

echo "\n";

call_user_func(array($classname, 's_echo_age'));

echo "\n";

call_user_func(array($c, 's_echo_age'));

通过此方式可以实现非常灵活的重载,但容易使逻辑变得负责,适度使用。

function call_it($func)

{

$args=func_get_args();

call_user_func_array($func,$args);

}

function add($a,$b)

{

echo $a+$b;

}

function sqr($a)

{

echo $a*$a;

}

call_it('add',1,2);

echo "\n";

call_it('sqr',2);

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template