__call ක්රමය
__call ක්රමය PHP හි මායා ක්රමයක් වන අතර එය පන්තියක නොපවතින හෝ ප්රවේශය නොලැබෙන ක්රමයකට ප්රවේශ වීමට උත්සාහ කිරීමේදී ස්වයංක්රීයව කැඳවනු ලැබේ. පළමු පරාමිතිය ලෙස එය කැඳවනු ලබන ක්රමයේ නම සහ දෙවන පරාමිතිය ලෙස තර්ක අරාව පිළිගනී.
වාක්ය රචනය
public function __call(string $name, array $arguments) {
// ක්රියාත්මක කිරීම
}
උදාහරණය
__call ක්රමයක් සහිත පන්තියක් නිර්මාණය කරමු, එය නොපවතින සියලුම ක්රම කැඳවීම් අතුරු අල්ලා ගනී:
<?php
class Test {
public function __call($name, $args) {
echo "කැඳවන ලද ක්රමය: " . $name . "\n";
echo "තර්ක: ";
print_r($args);
}
}
$test = new Test();
$test->nonExistentMethod('a', 'b', 123);
?>
කේතය ක්රියාත්මක කිරීමේ ප්රතිපලය:
Called method: nonExistentMethod
Arguments: ['a', 'b', 123]
උදාහරණය
__call භාවිතයෙන් සරල ක්රම ප්රතිනියෝජිතයක් ක්රියාත්මක කරමු:
<?php
class Calculator {
public function add($a, $b) {
return $a + $b;
}
}
class Math {
private $calculator;
public function __construct() {
$this->calculator = new Calculator();
}
public function __call($name, $args) {
if (method_exists($this->calculator, $name)) {
return call_user_func_array(
[$this->calculator, $name],
$args
);
}
throw new Exception("Method $name not found");
}
}
$math = new Math();
echo $math->add(2, 3);
?>
කේතය ක්රියාත්මක කිරීමේ ප්රතිපලය:
5
මෙයද බලන්න
-
__callStaticක්රමය,
ස්ථිතික ක්රම කැඳවීම් අතුරු අල්ලා ගනී -
__getක්රමය,
නොපවතින ගුණාංග වෙත ප්රවේශ වීම් අතුරු අල්ලා ගනී