【问题标题】:Calling Classes in foreach only last call works在 foreach 中调用类仅最后一次调用有效
【发布时间】:2012-06-22 13:21:58
【问题描述】:

大家好,

我编写了一个脚本,它读取包含一行或多行的字符串。然后将在数组中读取这些行以循环。每行包含一个类和一个在 foreach 中调用的方法。调用方法的结果保存在要返回的 var 中。

我的问题是现在只有最后一个调用被执行所有其他调用返回我之前该方法不存在,即使我更改行的顺序总是最后一个调用有效。这包括所有方法都存在并且有效。

线条看起来像这样

class_1/方法1 类_2/方法2 class_2/method1

我用 foreach 循环的给定数组看起来像这样

数组(

[0] => class_1/method1 [1] => class_2/method2 [2] => class_2/method1

现在我的代码像这样转换新数组中的每个项目

数组(

[0] => 类_1 [1] => 方法1

其中调用了class_1和method1

我的代码是这样的

    public function execute_lines($f){
     $cont = "";  // contains the results of all calls

     if($l = $this->get_line_array($f)){  // $l contains the array of all lines
        foreach($l as $k => $v){        
        if(strpos($v,"/")){     
         $a = explode("/",$v);  // $a contanis the array with the class and method and may be further data to be used in the methods called
         $c = ucfirst($a[0]);   // var of the Class
         $m = strtolower($a[1]);  // var of the methode
         unset($a[0],$a[1]);  // delete the first two items so that the array contains only further data

         if(method_exists($c,$m)){  // see if the method exists
            $x = new $c();  // instantiate the Class
            $cont .=  $x->e($m,$a);  // save result 
            print "-<br />";  // control if the method exits
         }else{
            print "/<br />";  // control if the method does not exists 
         }
        }
     }
    }   
    return $cont;  // returns the cont
    }

结果是

"/" “/” 然后只有最后一次调用的内容应该出现

感谢您的帮助

【问题讨论】:

    标签: php oop foreach


    【解决方案1】:

    如果您正在从文件中读取行,那么每行都会附加一个换行符(似乎只有最后一行没有)

    更改您的代码并重试

    foreach($l as $k => $v){     
        $v = trim($v); // trim whitespace
    
        if(strpos($v,"/")){
            ...
        }
    }
    

    【讨论】:

    • 嗨德国朗姆酒,这可能是我无法解决的解决方案,但我会尽快通知你
    • Hi German Rumm,我只是创建了一个环境来测试您的解决方案,而且它解决了问题。谢谢你为我节省了数小时的调试和搜索时间
    • 嗨 German Rumm,我在我的开发环境中尝试过,现在确实可以正常工作了,再次感谢
    猜你喜欢
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    • 2023-02-08
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多