3
Oct

Learn PHP return, Learn PHP series

In this lesson we’ll learn PHP return, the return statement is commonly used in functions/methods to return a value. You’ll notice many methods have a “return”. And in documentation for methods/functions most list the return value(s). This is a critically important part of learning an API, is being aware of what is being returned. Good documentation helps us a lot by saving us the time of trial and error to find out what a method returns.

To understand what “return” means picture you have an object House stored in $house. Now let’s say there is a method in the House class whose job is to go and get the latest price for this house and it’s name is “get_price()”.  The get_price() method might be loading the price from the database where the house is stored, or it might already have the value of the house price stored in a class property such as $price. Now because get_price() returns the value of the price such we will expect a float (numeric) value such as 145900.

Most commonly we will want to store the return value of a method. In this example we store the price in variable $price.

$price = $house->get_price();

What if we are in a view or template file and want to output the price? We could use:

print $house->get_price();

Now let’s look at the get_price() method:

public function get_price() {

return $this->price;

}

About Joel Milne
Lead developer at GoldHat Group.
No Comments

Leave a Comment

Your email address will not be published. Required fields are marked *