Private metoder i OOP i PHP
Private kan ikke bare være egenskaper, men også metoder. Vanligvis private gjør hjelpemetoder slik at de ved et uhell ikke kan bli kalt utenfra klassen.
La oss se på et eksempel. Anta at vi har følgende klasse:
<?php
class User {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function show() {
return $this->name;
}
}
?>
La oss lage en privat metode i denne klassen, som ved parameter vil ta imot en streng og gjøre den første bokstaven stor:
<?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);
}
}
?>
La oss bruke vår hjelpemetode inni en annen metode:
<?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);
}
}
?>
La oss teste. La oss opprette et objekt av vår klasse:
<?php
$user = new User('john');
?>
La oss kalle den offentlige metoden, som bruker hjelpemetoden:
<?php
echo $user->show();
?>
I følgende kode, gjør hjelpemetoden privat:
<?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 . '
;
}
}
?>