代码改变世界

php 接触的不常见函数

2020-07-11 02:52  天心PHP  阅读(152)  评论(0编辑  收藏  举报

constant

constant — 返回一个常量的值

constant ( string $name ) : mixed    通过 name 返回常量的值。

当你不知道常量名,却需要获取常量的值时,constant() 就很有用了。也就是常量名储存在一个变量里,或者由函数返回常量名。

<?php
define("MAXSIZE", 100);
echo MAXSIZE.'<br/>';
echo constant("MAXSIZE"); // same thing as the previous line
interface bar {
    const test = 'bar!';
}
class foo {
    const test = 'foo!';
}
$const = 'test';
var_dump(constant('bar::'. $const)); // string(7) "foobar!"
var_dump(constant('foo::'. $const)); // string(7) "foobar!"
?>

结果:100
100string(4) "bar!" string(4) "foo!"

 

array_walk()

对数组中的每个元素应用用户自定义函数:

语法:array_walk(array,myfunction,parameter...)

定义和用法

array_walk() 函数对数组中的每个元素应用用户自定义函数。在函数中,数组的键名和键值是参数。

注释:您可以通过把用户自定义函数中的第一个参数指定为引用:&$value,来改变数组元素的值(参见实例 2)。

提示:如需操作更深的数组(一个数组中包含另一个数组),请使用 array_walk_recursive() 函数。

<?php
function myfunction($value,$key,$p)//存在key和value 还可以多加一个参数
{
echo "$key $p $value<br>";
}
$a=array("a"=>"red","b"=>"green","c"=>"blue");
array_walk($a,"myfunction","has the value");
?>

只能带一个参数

array_map()

函数将用户自定义函数作用到数组中的每个值上,并返回用户自定义函数作用后的带有新值的数组。

语法:array_map(myfunction,array1,array2,array3...)

<?php
function myfunction($v)//只有value 没有key的
{
  return($v*$v);
}

$a=array(1,2,3,4,5);
print_r(array_map("myfunction",$a));
?>

结果

Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 )

array_filter()

用回调函数过滤数组中的元素:

array_filter() 函数用回调函数过滤数组中的元素,如果自定义过滤函数返回 true,则被操作的数组的当前值就会被包含在返回的结果数组中, 并将结果组成一个新的数组。如果原数组是一个关联数组,键名保持不变。

<?php
function myfunction($v) 
{
if ($v==="Horse")
    {
    return true;
    }
return false;
}
$a=array(0=>"Dog",1=>"Cat",2=>"Horse");
print_r(array_filter($a,"myfunction"));
?>

结果:

Array ( [2] => Horse )

call_user_func

call_user_func — 把第一个参数作为回调函数调用

error_reporting(E_ALL);
function increment(&$var)
{
    $var++;
}

$a = 0;
call_user_func('increment', $a);
echo $a."\n";
call_user_func_array('increment', array(&$a)); // You can use this instead before PHP 5.3
echo $a."\n";

 

 is_callable()

is_callable() 函数用于检测函数在当前环境中是否可调用。

is_callable() 函数验证变量的内容能否作为函数调用。 这可以检查包含有效函数名的变量,或者一个数组,包含了正确编码的对象以及函数名。

get_object_vars()

返回由对象属性组成的关联数组 ,在类内调用时,会返回所有的属性(private,protect,public), 在类外使用只返回public

array_chunk()

函数把一个数组分割为新的数组块。

instanceof

作用:(1)判断一个对象是否是某个类的实例,(2)判断一个对象是否实现了某个接口。

第一种用法:

<?php
$obj = new A();
if ($obj instanceof A) {
  echo 'A';
}

第二种用法:

<?php
interface ExampleInterface
{
   public function interfaceMethod();
 }
 class ExampleClass implements ExampleInterface
{
   public function interfaceMethod()
   {
     return 'Hello World!';
   }
 }
$exampleInstance = new ExampleClass();
 if($exampleInstance instanceof ExampleInterface){
   echo 'Yes, it is';
 }else{
   echo 'No, it is not';
} 
?>
输出结果:Yes, it is