0

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?

4
Contributors
10
Replies
11
Views
5 Years
Discussion Span
Last Post by Buppy
0

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'
)

Edited by pritaeas: n/a

0

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

0

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.

0

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.

0

try this

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

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

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) ?

0

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

0

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

Edited by pritaeas: n/a

0

@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"),
)
0

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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.