Defining methods
Learn to add methods (functions) inside a class.
Defining methods
A method is a function defined inside a class. A method starts with the function keyword; followed by the method name, parentheses and a body in curly braces.
Example: function showInfo() { echo "Product info"; }. Here showInfo is the method name; the parentheses are empty for now, for parameters. The method body can contain echo, return and other statements. Defining a method does not run it; it waits to be called.
Method body and parameters
The method body is the block of code between the curly braces. You can write output with echo, do calculations and return a value with return.
A method can take parameters in the parentheses. Example: function greet($name) { echo "Hello " . $name; }. A parameter is a value given from outside when the method is called. This lesson focuses on parameterless methods.
Exercise Add a method to the Product class
Define a class named Product. Add a method named showInfo; in the body write echo "Product info" . "\n";. Do not call the method yet. After the class, write echo "Method defined" . "\n";.
Show example solution
Inside class Product { } add function showInfo() { echo ...; }, then echo after the class.
Example solution:
<?php
// Define the Product class and the showInfo method
class Product {
function showInfo() {
echo "Product info" . "\n";
}
}
echo "Method defined" . "\n";
Test yourself
-
Match the parts of a method
- function
- Keyword
- showInfo
- Method name
- ()
- Parameter parentheses
- { echo ...; }
- Body
-
Complete the method definition
class Product { ____ showInfo() { echo "Product info"; } }Show answer
class Product { function showInfo() { echo "Product info"; } } -
Which is a valid method definition inside a class?
- function showInfo() { }
- method showInfo() { }
- def showInfo() { }
- showInfo() { }
Show answer
function showInfo() { } — Correct. The function keyword, method name, parentheses and braces form a method.