返回并回显多个变量

时间:2016-06-29 11:23:37

标签: php

我编写了以下PHP脚本,用于回显类Book中构造函数Book中捕获的所有三个变量。

我希望PHP回显所有这三个变量。但是,目前它只回应了三者中的一个。

以下是代码:

<?php

  class Book {

           protected $title;
           protected $author;
           protected $yearPublished;   

          function Book($title, $author, $yearPublished)
          {
           $this->title=$title;
           $this->author=$author;
           $this->yearPublished=$yearPublished;
          }

         function Summary()
         {
           return $this->title;
           return $this->author;
           return $this->yearPublished;
           sprintf($this->title, $this->author, $this->yearPublished);
          }
  }


$test= new Book("Pride and Prejudice","John Doe","2016");
$test->Summary();
echo $test->Summary();

3 个答案:

答案 0 :(得分:3)

  1. Summary()方法在第一个return

    之后退出
      

    如果在函数内调用,则return语句立即结束当前函数的执行,并返回其参数作为函数调用的值。

    你可能想要这个:

    function Summary()
    {
        return sprintf('%s %s %s', $this->title, $this->author, $this->yearPublished);
    }
    

    此外,您对sprintf()的电话错过了第一个参数($format)。

  2. 不要使用&#34;旧式&#34; (不包括PHP 5之前的)构造函数,因为它们已被弃用,请使用__construct()代替

      

    旧样式构造函数在PHP 7.0中已弃用,将在以后的版本中删除。你应该总是在新代码中使用__construct()。

答案 1 :(得分:1)

您必须将此功能更改为

function Summary(){
      return $this->title;
      return $this->author;
      return $this->yearPublished;
      sprintf($this->title, $this->author, $this->yearPublished);
}

function Summary(){
      return sprintf('%s %s %s',$this->title, $this->author, $this->yearPublished);
}

答案 2 :(得分:-1)

如果要将对象打印为字符串,则需要使用魔术方法__toString http://php.net/manual/en/language.oop5.magic.php#object.tostring

class Book
{
...
    public function __toString()
    {
        return sprintf(
            '%s %s %s',
            $this->title,
            $this->author,
            $this->yearPublished
        );
    }
...
}

$test = new Book("Pride and Prejudice","John Doe","2016");
echo $test;