PHP ֧�ֿɱ亯���ĸ������ζ�����һ������������Բ���ţ�PHP ��Ѱ���������ֵͬ���ĺ��������ҳ���ִ�������ɱ亯����������ʵ�ְ����ص����������������ڵ�һЩ��;��
�ɱ亯�������������� echo��print��unset()��isset()��empty()��include��require �Լ����Ƶ����Խṹ����Ҫʹ���Լ��İ�װ����������Щ�ṹ�����ɱ亯����
Example #1 �ɱ亯��ʾ��
<?php
function foo() {
echo "In foo()<br />\n";
}
function bar($arg = '') {
echo "In bar(); argument was '$arg'.<br />\n";
}
// ʹ�� echo �İ�װ����
function echoit($string)
{
echo $string;
}
$func = 'foo';
$func(); // This calls foo()
$func = 'bar';
$func('test'); // This calls bar()
$func = 'echoit';
$func('test'); // This calls echoit()
?>
Ҳ�����ÿɱ亯�����������һ������ķ�����
Example #2 �ɱ䷽������
<?php
class Foo
{
function Variable()
{
$name = 'Bar';
$this->$name(); // This calls the Bar() method
}
function Bar()
{
echo "This is Bar";
}
}
$foo = new Foo();
$funcname = "Variable";
$foo->$funcname(); // This calls $foo->Variable()
?>
�����þ�̬����ʱ����������Ҫ�Ⱦ�̬�������ȣ�
Example #3 Variable �����;�̬����ʾ��
<?php
class Foo
{
static $variable = 'static property';
static function Variable()
{
echo 'Method Variable called';
}
}
echo Foo::$variable; // This prints 'static property'. It does need a $variable in this scope.
$variable = "Variable";
Foo::$variable(); // This calls $foo->Variable() reading $variable in this scope.
?>
As of PHP 5.4.0, you can call any callable stored in a variable.
Example #4 Complex callables
<?php
class Foo
{
static function bar()
{
echo "bar\n";
}
function baz()
{
echo "baz\n";
}
}
$func = array("Foo", "bar");
$func(); // prints "bar"
$func = array(new Foo, "baz");
$func(); // prints "baz"
$func = "Foo::bar";
$func(); // prints "bar" as of PHP 7.0.0; prior, it raised a fatal error
?>
�μ� is_callable()��call_user_func()���ɱ������ function_exists()��
�汾 | ˵�� |
---|---|
7.0.0 | 'ClassName::methodName' is allowed as variable function. |
5.4.0 | Arrays, which are valid callables, are allowed as variable functions. |