Hi,

A little help here needed - i want to make a class variable (array). Some values are expected to be from a session variable.
Example

public $myArray = array(
'key1' => 'something',
'key2' => $_SESSION['something_else'],
)

With this i get an error about unexpected variable. Aynone knows how to solve this situation?

You get that notice because the session variable may not be set yet. You can do something like this:

public $myArray = array (
  'key1' => 'something',
  'key2' => isset($_SESSION['something_else']) ? $_SESSION['something_else'] : 'a default value'
)

Now i get "Parse error: syntax error, unexpected T_ISSET in
something.php on line n". Same with variable, just T_VARIABLE.

It may not be allowed to do that in the definition. You can move the initialization of your array to the constructor of the class.

The construct part won't work in this case. It is actuallt a cakePHP model class, and the array is expected to be filled before any function fires.

try this

if(isset($_SESSION['something_else']))
        $req=$_SESSION['something_else'];
    else
        $req='a default value';

    public $myArray = array (
    'key1' => 'something',
    'key2' => $req
    )

The construct part won't work in this case. It is actually a cakePHP model class, and the array is expected to be filled before any function fires.

Is it a static class (I am not familiar with cake) ?

Karthik_pranas, unfortunately does not work, i get the same error as with $_SESSION variable.
pritaeas, no, it's not a static classes.

Change your definition to:

public $myArray = array ();

Just put this in the constructor:

$this->myArray = array (
  'key1' => 'something',
  'key2' => (isset($_SESSION['something_else']) ? $_SESSION['something_else'] : 'a default value')
);

@Buppy, Did you check whether the session value is assigned and accessed ?
Use cakephp's native session method to access session values.
try print_r($this -> Session -> read()); to check the session varaible is assigned or not. Use cakephp's native method to get the session value,

$this -> Session -> read("something_else");

and also, declare the variable first rather than defining the variable,

public $myArray = array();
$myArray = array(
'key1' => 'something',
'key2' => $this -> Session -> read("something_else"),
)

Solved the issue, but instead of constructor used the cakePHP default model callback method beforeValidate();

public $myArray = array ();

public function beforeValidate() {
$this->myArray = array (
    'key1' => 'something',
    'key2' => $_SESSION['something_else']
    );
}

Thanks for the help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.