当我尝试以下代码时,我只得到第一个输出。我想将所有输出附加到数组self::$results
,以便相同的函数将返回该数组,但在运行脚本后,该函数返回数组但只返回第一个输出。这意味着,它只附加了第一个输出。
<?php
/**
* @author Ewoenam
* @copyright 2014
*
* @odj class book
*/
class book
{
/**
* @array static $alpha; holds array of accepted words
*/
public static $alpha = array();
/**
* @array static $result; holds array of correct answers
*/
public static $results;
/**
* @string protected $word; parametr
*/
protected $word;
/**
* @var static $alpha; holder of class instance getter
* returns self::getInstance
*/
public static $init;
/**
* @method static getInstance(); class instance getter
* returns self();
*/
function __construct()
{
self::$alpha = array('love','life','health','power','money','God');
}
public static function getInstance()
{
if (self::$init === null)
{
self::$init = new self();
return self::$init;
}
}
/**
* @method static check()
* takes 1 param; self::$word
* returns bool
*/
public static function check($word)
{
for($i=0;$i<=count(self::$alpha)-1;$i++)
{
if(similar_text($word,self::$alpha[$i]) === strlen($word))
{
return true;
}
}
}
/**
* @method static result()
* takes 1 param; self::check()
* returns bool
*/
public static function result($bool)
{
if($bool === true)
{
return 'correct';
}
else
{
return 'wrong';
}
}
/**
* @method static getter()
* takes 1 param; array of words to be searched
* returns array self::$results
*/
public static function getter($array)
{
self::$results = array();
for($i = 0;$i<=count($array)-1;$i++)
{
// i want to add more thn one answers to to $result array but i get only the first answer.
//how do i ddo it?
self::$results[] = self::result(book::check($array[$i]));
return self::$results;
}
}
}
$array = array('love','ama','kofi','money','health','God');
print_r(book::getInstance()->getter($array));
var_dump(book::check('love')) ;
?>
答案 0 :(得分:0)
您在for循环中拥有return
。这就是为什么当它第一次运行时,它会在那里返回函数,而不是继续循环。
将您的功能更改为此功能,它将按照您希望的方式运行:
/**
* @method static getter()
* takes 1 param; array of words to be searched
* returns array self::$results
*/
public static function getter($array)
{
self::$results = array();
for($i = 0;$i<=count($array)-1;$i++)
{
// i want to add more thn one answers to to $result array but i get only the first answer.
//how do i ddo it?
self::$results[] = self::result(book::check($array[$i]));
}
return self::$results;
}
答案 1 :(得分:0)
您从循环内部的$getter
返回,因此在添加第一个元素后返回。你应该完成循环,然后返回:
public static function getter($array)
{
self::$results = array();
for($i = 0;$i<=count($array)-1;$i++)
{
self::$results[] = self::result(book::check($array[$i]));
}
return self::$results;
}