0

I have a question when it comes to using classes, constructors and functions

I'm trying to use json_encode and echo the array out. Can anyone point me in the correct direction here? I don't really know what I'm doing wrong, I thought it was correct but I guess not. Any and all help is appreciated. Thanks.

No errors or output.

class information
{

    public $motd, $owner, $greeting;
    public $array;

    function __construct($motd, $owner, $greeting){
        $this->motd = $motd;
        $this->owner = $owner;
        $this->greeting = $greeting;
    }

    function test(){
       $array = array(
        'motd' => $motd,
        'owner' => $owner,
        'greeting' => $greeting
       );
       $pretty = json_encode($array);
       echo $pretty;
    }

}


$api = new information('lolol','losslol','lololol');
$api->test;
?>
3
  • 3
    You need to call the test method. $api->test(); Commented Jan 22, 2014 at 20:17
  • and you array will be empty should be: motd' => $this->motd, 'owner' => $this->owner, 'greeting' => $this->greeting Commented Jan 22, 2014 at 20:18
  • Remember to read a lot of code, and test a lot more. In that way you will learn better than asking for help at the first issue. Commented Jan 22, 2014 at 20:19

2 Answers 2

3

Two mistakes:

  1. You're missing $this:

    $array = array(
      'motd' => $this->motd,
      'owner' => $this->owner,
      'greeting' => $this->greeting
    );
    
  2. You need to call $api->test().
    Your current code only evalutes $api->test (which results in a reference to a function) and throws the value away.

Sign up to request clarification or add additional context in comments.

2 Comments

This was my problem, I'm sorry this was probably a waste of a post. Thank you.
@BlueFireMedia No problem, but please remember to accept an answer for every question you posted: how does accepting an answer work? (if there is an answer which seems sufficient for you)
1

You need to call the test method, and you need to refer to variables correctly:

class information
{

    public $motd, $owner, $greeting;
    public $array;

    function __construct($motd, $owner, $greeting){
        $this->motd = $motd;
        $this->owner = $owner;
        $this->greeting = $greeting;
    }

    function test(){
       $array = array(
        'motd' => $this->motd,  // note the $this->
        'owner' => $this->owner,  // note the $this->
        'greeting' => $this->greeting  // note the $this->
       );
       $pretty = json_encode($array);
       echo $pretty;
    }

}


$api = new information('lolol','losslol','lololol');
$api->test(); // note the ()
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.