user3147180
user3147180

Reputation: 943

How can I mention keyword arguments in php constructor?

I am new to PHP OOP.

I have this constructor

protected $path='default';  

function __construct($var1, $var2 ..){
        $this->var1=$var1;
        $this->var2=$var2;
    }

$obj = MyClass($var1='www')

I want that if I make object and don't pass any arguments then I get the object with empty values.

But if mention the properties in the constructor like above then the object should have those properties set.

Currently if I define the constructor with args and don't supply any then I get error .

Upvotes: 3

Views: 169

Answers (2)

You could make use func_get_args() in PHP

<?php
class foo
{

    private $arrParams;

    function __construct()
    {
        if (func_num_args() != 0) {
            $this->arrParams = $this->setValues(func_get_args());

        }
    }

    public function setValues($params)
    {
        return $params;
    }

    public function dispParams()
    {
        print_r($this->arrParams);
    }

    public function retVal($var)
    {
        return $this->arrParams[$var];
    }

}

$foo1 = new Foo(3, 45, 64, 34);
$foo1->dispParams();

OUTPUT :

Array
(
    [0] => 3
    [1] => 45
    [2] => 64
    [3] => 34
)

For getting a corresponding value from the array... You could just call

 $foo1->retVal(2); // Prints you 64

Upvotes: 2

Awlad Liton
Awlad Liton

Reputation: 9351

you need to declare class property like this:

class  yourClass{

protected $path='default';  
public $var1;
public $var2;
function __construct($var1="dd", $var2='ss'){
        $this->var1=$var1;
        $this->var2=$var2;
    }

}

$obj = new yourClass();
echo "without params: ".$obj->var1.$obj->var2;

$obj2 = new yourClass("sdf","sfdsdf");
echo " with params : ".$obj2->var1.$obj2->var2;

Demo

Upvotes: 0

Related Questions