0

How can I set a public variable class for use into more than one functions? The code below returns me the following error:

Parse error: syntax error, unexpected T_NEW in ...

class A {

  var $classB = new B();

  public function __Construct($param1){
    echo $this->classB->export($param1);
  }

  public function otherParam($param2){
    echo $this->classB->export($param2);
  }

}
volk
  • 63
  • 5

2 Answers2

1

You cannot instance objects like java. PHP doesn't allow you to initialize your variables to anything but strings or integers (and some really basic stuff).

You will have to use

private $classB;

and

public function __construct($param1){
    $this->classB = new B();
    echo $this->classB->export($param1);
}

inside of the constructor.

César
  • 370
  • 1
  • 9
0

$classB would be a local variabile in your code, and this it is not set.

You want to use $this -> classB.

Anyways you would like to inject an instance of B inside A, consider reading about dependency injection.

moonwave99
  • 21,957
  • 3
  • 43
  • 64