PHP如何为类中的变量设置默认值? [英] PHP how set default value to a variable in the class?

查看:38
本文介绍了PHP如何为类中的变量设置默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?

Why don't we get first and how set right default value variable $name only for class A?

我将不胜感激.

推荐答案

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

You can use a constructor to set the initial values (or pretty much do anything for that matter) as you need to like this:

class example
{

    public $name;

    public function __construct()
    {
        $this->name="first";
    }

}

然后您可以在其他函数中使用这些默认值.

Then you can use these default values in your other functions.

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.

这篇关于PHP如何为类中的变量设置默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆