PHP构造函数单个参数

时间:2013-05-14 17:22:25

标签: php json object foreach multidimensional-array

更新:我收到此php错误:尝试在此行获取非对象的属性:     if($ card-> name == $ fileRef){

我正在使用__construct(x='') { definition }在php中构建一个Object并调用函数$var = new Object('string');

构造函数接收一个字符串,即'file',它与相应的'file.php'相关。在json文件中有一个包含该类的所有可用file.php的目录,其中包含目录信息。

我正在捕捉错误,也许是我的语法? ......现在给我两天,想要挥杆?

public function __construct($ctitle = '')
{
    $fileRef = $ctitle.'php';

    //Get the json card directory
    $this->cardDirLocation = 'thisismyserver.com/CardDir.json';
    $this->cardDir = file_get_contents($this->cardDirLocation);
    $this->cardArray = json_decode($this->cardDir, true);


    //Find the card listing from CardDir.json based on form response input and construct a Card class instance or use the main page (default)
    foreach ($this->cardArray['Cards'] as $key => $val) { //search through each card IS THIS MY ERR??
        if ($card->name == $fileRef){ //if the name matches a name in the cardDir.json file
            //Fill Values
        }
                    if ($this->title == ''){ //or if there is no title
            $this->title = 'Get Started at The Home Page'; //refer to default values -> the home page
            $this->dir = 'cards/start/';
            $this->name = 'start.php'; ...etc 

错误:我无法获取$ fileRef变量以匹配json文件数组中的任何内容,因此它总是进入'else if'默认值。 json文件看起来像这样:

  

{ “卡”:[{ “标题”: “东西”,              “名”: “file.php”,              “目录”: “somefile / DIR /这里/”             },             {“title”:“与某事不同”,              “名”:“xfiles.php”              “dir”:“somefile / dir / there /”...... etc

1 个答案:

答案 0 :(得分:0)

在返回或设置catchall case之前,您可能想要遍历整个数组。以下是如何操作:

foreach ($this->cardArray['Cards'] as $card) {
    if ($card->name == $fileRef) {
    // Your success actions here
     return true;
    }
}
 // Your failure actions here. This will only be reached if the foreach loop found nothing.