Search⌘ K
AI Features

Adding Methods in a Class

Explore how to add methods to PHP classes by defining public functions with proper naming conventions. Understand how to create objects and call class methods to perform actions, gaining foundational skills in object-oriented PHP.

The classes most often contain functions. A function inside a class is called a method.

How to add a method in class?

In line 7, we add the method hello() to the class with the prefix public.

PHP
<?php
class Car {
public $comp;
public $color = "beige";
public $hasSunRoof = true;
public function hello()
{
return "beep";
}
}
?>
  • We put the public keyword in front of a method.
  • The naming convention is to start the function name with a lower case letter.
  • If the name contains more than one word, all of the words start with an upper case letter, except for the first word. For example, helloUser() or flyPanAm()

How to access a method of a class?

We can approach the methods similar to the way that we approach the properties, but we first need to create at least one object from the class.

PHP
<?php
class Car {
public $comp;
public $color = "beige";
public $hasSunRoof = true;
// hello() function
public function hello()
{
return "beep";
}
}
// Creating objets of Car class
$car1 = new Car ();
$car2 = new Car ();
// Calling hello() method of car1 object
echo $car1 -> hello();
echo "\n";
// Calling hello() method of car2 object
echo $car2 -> hello();
?>

We called the hello() method of two car objects $car1 and $car2. Each object displays the “beep”.

In this chapter, we have done our first steps into the world of object oriented PHP by learning about classes and about the objects that can be created out of them.