ArsedianIvan
ArsedianIvan

Reputation: 399

Returning and Echoing multiple variables

I've written the following PHP script which is intended to echo all three variables that are captured in the constructor Book within the class Book.

I'd like PHP to echo all the three variables. However, at the moment it only echoes one of the three.

Here is the code:

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

Upvotes: 1

Views: 69

Answers (3)

Amit Ray
Amit Ray

Reputation: 3485

You have to change this function to

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

To

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

Upvotes: 1

Shira
Shira

Reputation: 6560

  1. the Summary() method exits after the first return

    If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call.

    You probably wanted this:

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

    Also your call to sprintf() was missing the first argument ($format).

  2. don't use "old-style" (pre-PHP 5) constructors as they are deprecated, use __construct() instead

    Old style constructors are DEPRECATED in PHP 7.0, and will be removed in a future version. You should always use __construct() in new code.

Upvotes: 3

newage
newage

Reputation: 909

You need to use magic method __toString if you want to print object as string 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;

Upvotes: -1

Related Questions