【问题标题】:PHP how set default value to a variable in the class?PHP如何为类中的变量设置默认值?
【发布时间】:2025-12-28 22:10:06
【问题描述】:
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

如果有任何帮助,我将不胜感激。

【问题讨论】:

  • $this->name$name 是两个不同的变量...
  • @deceze 我知道,但是如何在类中设置打印$name 的变量的默认值是first?如果 make public $name; $this->name='first'; 不会打印 first
  • 我是说你需要在test1() 函数中使用$this->name 而不是$name。另一部分很好,您可以将其恢复为初始版本。
  • @deceze 好吧,我理解你,我理解这是如何工作的。谢谢!

标签: php class variables


【解决方案1】:

您可以根据需要使用构造函数来设置初始值(或者几乎可以做任何事情):

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.

【讨论】:

    【解决方案2】:

    您有两个选项来设置类属性的默认值:

    选项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();
    

    【讨论】:

      【解决方案3】:

      使用isset() 为可能已经有值的变量分配默认值:

      if (! isset($cars)) {
          $cars = $default_cars;
      }
      

      使用三元 (a ? b : c) 运算符为新变量赋予一个(可能是默认值)值:

      $cars = isset($_GET['cars']) ? $_GET['cars'] : $default_cars;
      

      【讨论】:

      • 这没有回答原始问题。请再看看这个问题。 无论如何,如果问题不同,那将是一个很好的答案。 :)