DWils
DWils

Reputation: 398

passing $_POST to class constructor by default

For example, when using this code:

function __construct($args = '') {

it works fine if I instantiate the class with $obj = new class_name($_POST), but when I use:

function __construct($args = $_POST) {

I get an unexpected T_VARIABLE error. Is there a particular reason why this doesn't work?

Upvotes: 1

Views: 956

Answers (2)

sectus
sectus

Reputation: 15464

The default value must be a constant expression, not (for example) a variable, a class member or a function call.

http://www.php.net/manual/en/functions.arguments.php

You could use something like this

function __construct(array $args = null) {
    if (is_null($args))
        $args = $_POST;

Upvotes: 4

Mir Adnan
Mir Adnan

Reputation: 884

Better use it inside the constructor, $_POST can be accessed inside Objects.

Upvotes: 0

Related Questions