array_map不能在类中工作 [英] array_map not working in classes
问题描述
我试图创建一个类来处理数组,但我似乎无法得到 array_map()
来处理它。
<?php
//创建测试数组
$ array = array(1,2,3,4,5,6 ,7,8,9,10);
//创建测试类
class test {
//变量来保存类中的数组
public $ classarray;
//函数用给定的数组调用array_map函数
公共函数添加($ data){
$ this-> classarray = array_map($ this-> dash (),$ data);
}
//破折号函数在输入数组的两边添加一个 -
public function dash($ item){
$ item2 = ' - '。 $ item。 - ;
返回$ item2;
}
}
//转储起始数组
var_dump($ array);
//增加一行
echo'< br />';
//创建类对象
$ test = new test();
//类函数添加
$ test->添加($ array);
//应该输出数组值为-1 - , - 2 - , - 3 - , - 4 - ...
var_dump($ test-> classarray);
输出
array(10){[0] => int(1)[1] => int(2)[2] => int(3)[3] => int(4)[4] => int(5)[5] => int(6)[6] => int(7)[7] => int(8)[8] => int(9)[9] => int(10)}
警告:缺少test :: dash()的参数1,在D: \xampp\htdocs\trainingdvd\arraytesting.php on line 11 and defined in D:\xampp\htdocs\trainingdvd\arraytesting.php on line 15
警告:array_map()期望参数1是一个有效的回调,函数' - '未找到或D中无效的函数名称:\xampp\ htdocs \trainingdvd\arraytesting.php on line 11 NULL
我在做什么错误或者这个函数不能在类中工作?
您以错误的方式指定 dash
作为回调。
这不起作用:
$ this-> classarray = array_map($ this-> dash(),$ data);
这样做:
$ this-> classarray = array_map(array($ this,'dash'),$ data);
阅读回调可能需要的不同形式 here 。
I am trying to create a class to handle arrays but I can't seem to get array_map()
to work in it.
<?php
//Create the test array
$array = array(1,2,3,4,5,6,7,8,9,10);
//create the test class
class test {
//variable to save array inside class
public $classarray;
//function to call array_map function with the given array
public function adding($data) {
$this->classarray = array_map($this->dash(), $data);
}
// dash function to add a - to both sides of the number of the input array
public function dash($item) {
$item2 = '-' . $item . '-';
return $item2;
}
}
// dumps start array
var_dump($array);
//adds line
echo '<br />';
//creates class object
$test = new test();
//classes function adding
$test->adding($array);
// should output the array with values -1-,-2-,-3-,-4-...
var_dump($test->classarray);
This outputs
array(10) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) [4]=> int(5) [5]=> int(6) [6]=> int(7) [7]=> int(8) [8]=> int(9) [9]=> int(10) }
Warning: Missing argument 1 for test::dash(), called in D:\xampp\htdocs\trainingdvd\arraytesting.php on line 11 and defined in D:\xampp\htdocs\trainingdvd\arraytesting.php on line 15
Warning: array_map() expects parameter 1 to be a valid callback, function '--' not found or invalid function name in D:\xampp\htdocs\trainingdvd\arraytesting.php on line 11 NULL
What am I doing wrong or does this function just not work inside classes?
You are specifying dash
as the callback in the wrong way.
This does not work:
$this->classarray = array_map($this->dash(), $data);
This does:
$this->classarray = array_map(array($this, 'dash'), $data);
Read about the different forms a callback may take here.
这篇关于array_map不能在类中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!