Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

I would be grateful for any help.

like image 238
Brown Avatar asked Jan 20 '15 01:01

Brown


People also ask

How do you assign default values to variables?

The OR Assignment (||=) Operator The logical OR assignment ( ||= ) operator assigns the new values only if the left operand is falsy. Below is an example of using ||= on a variable holding undefined . Next is an example of assigning a new value on a variable containing an empty string.

How do you declare a variable inside a class in PHP?

The var keyword in PHP is used to declare a property or variable of class which is public by default. The var keyword is same as public when declaring variables or property of a class.

What is the default value of variable in PHP?

Uninitialized variables have a default value of their type depending on the context in which they are used - booleans default to false , integers and floats default to zero, strings (e.g. used in echo) are set as an empty string and arrays become to an empty array.

What is the default value for a class object?

In Java, class and instance variables assume a default value (null, 0, false) if they are not initialized manually. However, local variables aren't given a default value. You can declare but not use an uninitialised local variable. In Java, the default value of any object is null.


1 Answers

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.
like image 144
Fluffeh Avatar answered Sep 28 '22 02:09

Fluffeh