Note that there are some explanatory texts on larger screens.

plurals
  1. POget value of private var in a class through typehinted object to assign it in php 5.3
    text
    copied!<p>I have been reading Rafactoring by Martin Fowler and in the beginning of the book he uses an example application (written in Java), which I am trying to convert over to PHP for training purposes. (I have trimmed the code down to make this question, but it works if the variables are public.)</p> <p>The trouble is to create a statement I need access to a value (see switch) using method getCode() of Movie class since $code is private. (Of course if all of the variables were public the code below would work, but I want to keep them private.)</p> <p>Can someone please shed some light on how I would access the private variable calling the getCode() method of Movie from the switch in statement(). (Or if there is a better way to do it, let me know.)</p> <pre><code>class Movie { private $title; private $code; public function __construct($title, $code) { $this-&gt;title = $title; $this-&gt;code = $code; } public function getCode() { return $this-&gt;code; } public function getTitle() { return $this-&gt;title; } } class Rental { private $movie; // will carry a Movie object private $days; public function __construct(Movie $movie, $days) { $this-&gt;movie = $movie; $this-&gt;days = $days; } public function getMovie() { return $this-&gt;movie; } } class Customer { private $name; private $rentals; // will be a collection of Rental Objects public function __construct($name) { $this-&gt;name = $name; } public function addRental(Rental $rental) { $this-&gt;rentals[] = $rental; } public function statement() { $thisAmount = 0; foreach ($this-&gt;rentals as $each) { // what is the better way to call this value?????? switch ($each-&gt;movie-&gt;code) { case 1: $thisAmount+= ($each-&gt;days - 2) * 1.5; break; case 2: $thisAmount += $each-&gt;days * 3; break; case 3: $thisAmount += 1.5; break; } // show figures for this rental $result = "\t" . $each-&gt;movie-&gt;title . "\t" . $thisAmount . "\n"; } return $result; } } // pick a movie $movie = new Movie('Star Wars', 0); // now rent it $rental = new Rental($movie, '2'); // now get statement $customer = new Customer('Joe'); $customer-&gt;addRental($rental); echo $customer-&gt;statement(); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload