使用类和函数

时间:2014-01-22 20:15:41

标签: php

在使用类,构造函数和函数时,我有一个问题

我正在尝试使用json_encode并将数组回显出来。 谁能指出我在这里的正确方向?我真的不知道我做错了什么,我认为这是正确的,但我猜不是。任何和所有的帮助表示赞赏。感谢。

没有错误或输出。

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

2 个答案:

答案 0 :(得分:3)

两个错误:

  1. 您错过了$this

    $array = array(
      'motd' => $this->motd,
      'owner' => $this->owner,
      'greeting' => $this->greeting
    );
    
  2. 您需要致电$api->test()
    您当前的代码仅评估$api->test(这会导致对函数的引用)并抛出该值。

答案 1 :(得分:1)

您需要调用test方法,并且需要正确引用变量:

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 ()
?>
相关问题