值通过使用可选的返回语句返回。可以返回包括数组和对象的任意类型。返回语句会立即中止函数的运行,并且将控制权交回调用该函数的代码行
如果省略了 return,则返回值为 null。
<?php
function square($num)
{
return $num * $num;
}
echo square(5); // outputs '25'.
?>
函数不能返回多个值,但可以通过返回一个数组来得到类似的效果。
<?php
function small_numbers()
{
return [0, 1, 2];
}
// 使用短数组语法将数组中的值赋给一组变数
[$zero, $one, $two] = small_numbers();
// 在 7.1.0 之前,唯一相等的选择是使用 list() 结构
list($zero, $one, $two) = small_numbers();
?>
从函数返回一个引用,必须在函数声明和指派返回值给一个变量时都使用引用运算符 &
<?php
function &returns_reference()
{
return $someref;
}
$newref =& returns_reference();
?>
PHP 支持可变函数的概念。就是说如果一个变量名後有圆括号,PHP 就会先去寻找这个变数名称的函数执行。可变函数可以用来实现包括回调函数,以及函数表在内的一些用途。
来看看范例
<?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()
?>
<?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()
?>
当调用静态方法时,函数调用要比静态属性优先
<?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.
?>
<?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"
// 这样可是会出错的哦,没有先实体化类别
$func = array("Foo", "baz");
$func(); // Uncaught Error: Non-static method Foo::baz() cannot be called statically in ....
?>
PHP 有很多标准的函数和结构。还有一些函数需要和特定地 PHP 扩展模块一起编译,否则在使用它们的时候就会得到一个致命的“未定义函数”错误。
例如要连接MySQL,要使用 mysqli_connect() 函数,就需要在编译 PHP 的时候加上 MySQLi 支持。可以使用 phpinfo() 或者 get_loaded_extensions() 可以得知 PHP 加载了那些扩展库
使用生物特徵来区分生物个体,常见的有使用声音、人脸、虹膜、签名(字迹)等方式,在上述的方法中,人脸辨...
tags: 2021永丰金铁人赛 初学者在使用的时候,可能会遇到下列错误讯息: File "...
GitHub Repo https://github.com/b2etw/Spring-Kotlin...
讲到云端相关的议题,一定会看到的就是 IaaS 、 PaaS 与 SaaS。这几个名词可以算是云端的...
这次参赛主轴分为三大部份: Kotlin Android Jetpack Tensorflower ...