⊗ppOpBsPM 11 of 107 menu

Private Methods in OOP in PHP

Not only properties but also methods can be private. Usually, helper methods are made private so that they cannot be accidentally called from outside the class.

Let's look at an example. Suppose we have the following class:

<?php class User { private $name; public function __construct($name) { $this->name = $name; } public function show() { return $this->name; } } ?>

Let's make a private method in this class, which will take a string as a parameter and capitalize its first character:

<?php class User { private $name; public function __construct($name) { $this->name = $name; } public function show() { return $this->name; } private function cape($str) { return mb_strtoupper(mb_substr($str, 0, 1)) . mb_substr($str, 1); } } ?>

Let's use our helper method inside another method:

<?php class User { private $name; public function __construct($name) { $this->name = $name; } public function show() { return $this->cape($this->name); } private function cape($str) { return mb_strtoupper(mb_substr($str, 0, 1)) . mb_substr($str, 1); } } ?>

Let's test it. Let's create an object of our class:

<?php $user = new User('john'); ?>

Let's call the public method that uses the helper:

<?php echo $user->show(); ?>

In the following code, make the helper method private:

<?php class Employee { public function __construct($name, $salary) { $this->name = $name; $this->salary = $salary; } public function getSalary() { return $this->addSign($this->salary); } public function addSign($num) { return $num . ' ; } } ?>
byenru