PHP හි OOP හි පුද්ගලික ක්රම
ගුණාංග පමණක් නොව, ක්රම ද පුද්ගලික විය හැකිය. සාමාන්යයෙන් පුද්ගලික කරනු ලබන්නේ උපකාරී ක්රම වන අතර, එමගින් ඒවා වරදවා වරදවා හඳුනාගත නොහැකි වන පරිදි පන්තියෙන් පිටතින් කැඳවීමට ඉඩ නොදේ.
අපි උදාහරණයක් බලමු. අපට පහත පන්තිය ඇතැයි සිතමු:
<?php
class User {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function show() {
return $this->name;
}
}
?>
මෙම පන්තියේ පුද්ගලික ක්රමයක් සාදමු, එය පරාමිතියක් ලෙස පිළිගනු ඇත දර්ශකය සහ එහි පළමු සංකේතය විශාල අකුරෙන් ලියන්න:
<?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);
}
}
?>
අපගේ උපකාරී භාවිතා කරමු වෙනත් ක්රමයක් තුළ ක්රමය:
<?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);
}
}
?>
අපි පරීක්ෂා කර බලමු. අපි සාදන්නෙමු අපගේ පන්තියේ වස්තුව:
<?php
$user = new User('john');
?>
පොදු ක්රමය කැඳවමු, උපකාරී භාවිතා කරයි:
<?php
echo $user->show();
?>
පහත කේතයේ උපකාරී කරන්න
<?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 . '
;
}
}
?>