PHP OOP တွင် Variable မှ Property Name ကိုရယူခြင်း
Object များ၏ properties များကို
Variable တစ်ခုထဲမှအမည်ယူ၍လည်းခေါ်ယူအသုံးပြုနိုင်သည်။
ဤသို့ပြုလုပ်နည်းကိုကြည့်ရှုကြပါစို့။
ကျွန်ုပ်တို့၌ User Class တစ်ခုရှိသည်ဆိုပါစို့။
<?php
class User
{
public $name;
public $surn;
public function __construct($name, $surn)
{
$this->name = $name;
$this->surn = $surn;
}
}
?>
ဤ Class ၏ Object တစ်ခုကိုဖန်တီးကြပါစို့။
<?php
$user = new User('john', 'smit');
?>
၎င်း၏ Property တန်ဖိုးကိုထုတ်ပြကြပါစို့။
<?php
echo $user->name; // 'john' ကိုထုတ်ပြမည်
?>
ကျွန်ုပ်တို့၌ Property ၏အမည်ကိုသိမ်းဆည်းထားသော Variable တစ်ခုရှိသည်ဆိုပါစို့။
<?php
$prop = 'name';
?>
ယခု Variable ၏တန်ဖိုးကို Property အမည်အဖြစ် အသုံးပြုကြည့်ကြပါစို့။
<?php
$prop = 'name';
echo $user->$prop; // 'john' ကိုထုတ်ပြမည်
?>
အောက်ပါ Class ကိုပေးထားသည်။
<?php
class Employee
{
public $name;
public $salary;
public function __construct($name, $salary)
{
$this->name = $name;
$this->salary = $salary;
}
}
?>
အောက်ပါ Variable များကိုပေးထားသည်။
<?php
$prop1 = 'name';
$prop2 = 'salary';
?>
Employee Class ၏ Object တစ်ခုကိုဖန်တီးပါ၊
ထို့နောက် ၎င်း၏ properties များကို
အထက်ပါ variable များမှတစ်ဆင့်ခေါ်ယူပါ။