DataBox DataBox - 5 months ago 10
PHP Question

Call PHP function variable from separate file

I have a class function that calls JSON from a URL. That function then sets a list of variables from the results of the JSON.

What I am attempting to do is call back one of those strings from inside of another file (index.html). I do not receive any errors back, however the results are blank.

I'm sure it's not due to the json command because it works properly when not placed inside of a class/function. To be sure I attempted to add

$somestring4 = 'this is string 4'
into the ClassFile.php and call it - it was also blank.



Here is my code...

ClassFile.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;
?>


Call from Index.html

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




Thanks for the help and sorry for the ignorance.

Answer
<?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;
?>
Comments