【问题标题】:PHP constructor function single paramPHP构造函数单参数
【发布时间】:2013-05-09 02:07:42
【问题描述】:

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

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

构造函数接收一个字符串,即与相应的“file.php”相关的“file”。在一个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 文件如下所示:

{"卡片":[{"title":"某事", “名称”:“文件.php”, “目录”:“某个文件/目录/这里/” }, {"title":"不同于某物", "名称":"xfiles.php", "dir":"somefile/dir/there/" ...等

【问题讨论】:

  • echo: $val['name']这行输出什么?
  • 谢谢 已回答。

标签: php json object foreach multidimensional-array


【解决方案1】:

您可能希望在返回或设置一个包罗万象的情况之前遍历整个数组。这样做的方法如下:

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.

【讨论】:

  • Explosion Pills:调试回显语句输出 start.php(我想要的)它在 foreach 中不匹配。 Sabastien:是的,你完全正确。我犯了一个人为错误,您发现了这一点,就像我发布问题时一样。我会做一些改变并保持发布*
  • 无论发生什么,您的 start.php 输出都将在 foreach 之后完成。否则,你的 foreach 只会跨越数组的第一个元素。
  • 问题在于 if else 的语法和我想要的输出。我还必须访问解码后的 json,例如 $this->cardArray['Cards'] as $card=>$val ... $this->name = $val['name'];
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-07
  • 2022-09-23
  • 1970-01-01
相关资源
最近更新 更多