Steven Hammons
Steven Hammons

Reputation: 1810

Is there a reason I cannot declare public in class?

class struct {
public $variable=$_SESSION['Example'];
}

How do I call a Session and put it into a variable in php classes?

Upvotes: 3

Views: 186

Answers (4)

Naveed
Naveed

Reputation: 42143

Read http://php.net/manual/en/language.oop5.php

class struct {
 public $variable;
 public function __construct(){
   session_start();
   $this->variable = $_SESSION['Example'];
 }
}

Upvotes: 6

Long Ears
Long Ears

Reputation: 4896

Properties can only have literal defaults, not arbitrary expressions. The simplest way to do this is:

class Struct {
    public $variable;

    public function __construct() {
        $this->variable = $_SESSION['Example'];
    }
}

Upvotes: 3

alex
alex

Reputation: 490657

You can not set any properties in the definition unless they are a constant, e.g. TRUE, array(), etc.

In the __construct() you may set it.

Upvotes: 2

philwinkle
philwinkle

Reputation: 7056

class struct {
  public $variable;

  public function __construct(){
    session_start();
    $this->variable = $_SESSION['Example'];
  }
}

Upvotes: 3

Related Questions