PHP对象从数组中获取值

时间:2013-05-19 13:44:04

标签: php object

我写了一个这样的课: -

class Mail{
    function register()
    {
    return array('message_subject'=>$message_subject,'message_content'=>$message_content);
    }
}

然后在主页面上,我尝试了: -

echo Mail::register();

并且主页面给了我“Array”的值。

我该如何修改Mail :: register();这样它可以分别收到“message_subject”和“message_content”吗?

3 个答案:

答案 0 :(得分:0)

将Mail :: register()分配给一个变量,然后打印它,因为你正在从中重新调整数组。数组始终由print_f打印,而不是由echo打印     

$mail = Mail::register();
echo'<pre>';
print_r($mail);
echo '</pre>';
?>

答案 1 :(得分:0)

带参数

class Mail{
    function register($message_subject, $message_content)
    {
        return array('message_subject'=>$message_subject,'message_content'=>$message_content);
    }
}

echo Mail::register('foo', 'bar')

或使用会员字段

class Mail {
  private $message_subject;
  private $message_content;

  public function __construct($subject, $content) {
    $this->message_subject = $subject;
    $this->message_content = $content;
  }

  function register() {
    return array('message_subject' => $this->message_subject,'message_content' => $this->message_content);
  }
}

$mail = new Mail('foo', 'bar');
$mail->register();

答案 2 :(得分:0)

你可以尝试

$mail = new Mail();
list($subject, $content) = $mail->register();

或者

$mail = new Mail();
$data = $mail->register();
printf("%s \n %s", $data['message_subject'], $data['message_content']);

我的猜测是你的班级是这样的:

class Mail {
    private $subject, $content;

    function __construct() {
        $this->subject = "Demo";
        $this->content = "Hello World";
    }

    function register() {
        return array(
                'message_subject' => $this->subject,
                'message_content' => $this->content
        );
    }
}