[英]PHP how set default value to a variable in the class?
class A{
public $name;
public function __construct() {
$this->name = 'first';
}
public function test1(){
if(!empty($_POST["name"]))
{
$name = 'second';
}
echo $name;
}
$f = new A;
$f->test1();
為什么我們不first
獲取以及如何為 A 類設置正確的默認值變量$name
?
我將不勝感激任何幫助。
您可以根據需要使用構造函數來設置初始值(或幾乎為此做任何事情):
class example
{
public $name;
public function __construct()
{
$this->name="first";
}
}
然后您可以在其他函數中使用這些默認值。
class example
{
public $name;
public function __construct()
{
$this->name="first";
}
public function test1($inputName)
{
if(!empty($inputName))
{
$this->name=$inputName;
}
echo "The name is ".$this->name."\r\n";
}
}
$ex=new example();
$ex->test1(" "); // prints first.
$ex->test1("Bobby"); // prints Bobby
$ex->test1($_POST["name"]); // works as you expected it to.
您有兩個選項可以設置類屬性的默認值:
選項1:在參數級別設置。
class A
{
public $name = "first";
public function test1()
{
echo $this->name;
}
}
$f = new A();
$f->test1();
選項 2:每次創建新實例時總是執行魔術方法 __construct()。
class A
{
public $name;
public function __construct()
{
$this->name = 'first';
}
public function test1()
{
echo $this->name;
}
}
$f = new A();
$f->test1();
使用isset()
將默認值分配給可能已經有值的變量:
if (! isset($cars)) {
$cars = $default_cars;
}
使用三元(a ? b : c)
運算符為新變量指定一個(可能是默認值)值:
$cars = isset($_GET['cars']) ? $_GET['cars'] : $default_cars;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.