【问题标题】:Call PHP function variable from separate file从单独的文件中调用 PHP 函数变量
【发布时间】:2016-06-04 17:34:14
【问题描述】:

我有一个从 URL 调用 JSON 的类函数。然后,该函数根据 JSON 的结果设置变量列表。

我正在尝试做的是从另一个文件 (index.html) 中回调其中一个字符串。我没有收到任何错误回复,但是结果是空白的。

我确定这不是由于 json 命令,因为它在未放置在类/函数内部时可以正常工作。可以肯定的是,我尝试将 $somestring4 = 'this is string 4' 添加到 ClassFile.php 并调用它 - 它也是空白的。


这是我的代码...

类文件.php

<?php
class newClass { 

Function newFunction(){
$jsonFetched = file_get_contents('http://url.com/file.json'); //<== MISSING SINGLE QUOTES ADDED FOR CODE-READABILITY...
$jsonQuery = json_decode($jsonFetched);

$someString1 = $jsonQuery->level1->level2->string1 ;
$someString2 = $jsonQuery->level1->level2->string2 ;
$someString3 = $jsonQuery->level1->level2->string3 ;
    }
}       

$foo = new newClass; 
?>

从 Index.html 调用

<?php  
include($sitePath . '/classes/ClassFile.php') ;
$refClass = new newClass();
$someString3 = $refClass->newFunction();
echo $someString3;
?>


感谢您的帮助,并为无知感到抱歉。

【问题讨论】:

  • $someString1 !== $someString3;您的 newFunction() 也不会返回任何要分配给任何变量的东西;更不用说newFunction()第一行中缺少的引号
  • 新的 newClass();而不是新的 newClass);
  • 它只是语法,这就是我添加评论而不是答案的原因
  • 在 PHP 中预期输出时的空白页通常意味着致命错误(已经指出的几个语法/解析错误)。始终在开发和测试代码时,启用 PHP 的错误显示,在你的脚本顶部 error_reporting(E_ALL); ini_set('display_errors', 1); - 你会看到 PHP 抱怨一些事情,比如在 file_get_contents() 调用中缺少引号。
  • 抱歉,这些是我在为帖子重写代码时出现的拼写错误。

标签: php html json


【解决方案1】:
<?php
class newClass { 
  public $jsonFetched = '';
  public $jsonQuery = '';
  public $someString1 = '';
  public $someString2 = '';
  public $someString3 = '';


function newFunction(){
    $jsonFetched = file_get_contents('http://url.com/file.json');
       $jsonQuery = json_decode($jsonFetched);

       $this->someString1 = $jsonQuery->level1->level2->string1 ;
       $this->someString2 = $jsonQuery->level1->level2->string2 ;
       $this->someString3 = $jsonQuery->level1->level2->string3 ;
    }
}       


?>

<?php  
include($sitePath . '/classes/ClassFile.php') ;
$refClass = new newClass();
$refClass->newFunction();
echo $refClass->someString3;
?>

【讨论】:

  • 这是 PHP。 $this-&gt; 不是 $this.
  • 您在public someString3=''; 缺少$
  • 这似乎让我朝着正确的方向前进!但是,我得到 Notice: Undefined variable: jsonFetched in /ClassFile.php 指的是$this-&gt;jsonFetched = file_get_contents('http://url.com/file.json'); 当通过$this-&gt;someString4 = 'this is string 4'; 定义变量时,它工作得很好。
  • 从 jsonFetched 和 jsonQuery 中删除 this-&gt; 修复了错误。感谢您的帮助! @Khaled
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-10
  • 2013-05-08
  • 1970-01-01
  • 1970-01-01
  • 2013-03-27
  • 1970-01-01
相关资源
最近更新 更多