57

配列を処理するクラスを作成しようとしていますが、それで作業できないようですarray_map()

<?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);

これは出力します

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

私は何を間違っていますか、またはこの関数はクラス内で機能しませんか?

4

6 に答える 6

154

dashコールバックとして間違った方法で指定しています。

これは動作しません:

$this->classarray = array_map($this->dash(), $data);

これは次のことを行います。

$this->classarray = array_map(array($this, 'dash'), $data);

コールバックのさまざまな形式については、こちらを参照してください

于 2011-03-24T16:20:41.280 に答える
2

array_map($this->dash(), $data)引数なしで呼び出し$this->dash()、戻り値をコールバック関数として使用して、配列の各メンバーに適用します。array_map(array($this,'dash'), $data)代わりに欲しい。

于 2011-03-24T16:21:45.847 に答える
1

読まなければならない

$this->classarray = array_map(array($this, 'dash'), $data);

array-thing は、オブジェクト インスタンス メソッドのPHP コールバックです。通常の関数へのコールバックは、関数名 ( 'functionName') を含む単純な文字列として定義されますが、静的メソッド呼び出しは、array('ClassName, 'methodName')またはそのような文字列として定義されます'ClassName::methodName'(これは PHP 5.2.3 以降で機能します)。

于 2011-03-24T16:20:57.830 に答える