FrediWeber
FrediWeber

Reputation: 1099

How can I define a variable before create the class?

How can I define a variable before or while initializing the class?

<?php
class class{
 public $var;
 public function __construct(){
  echo $this -> var;
 }
}
$class = new class;
$class -> var = "var";
?>

Upvotes: 1

Views: 187

Answers (4)

Joseph
Joseph

Reputation: 1963

class myClass {
    protected $theVariable;

    protected function myClass($value) {
        $this->$theVariable = $value;
    }
}


$theVariable = 'The Value';

$theClass = new myClass($theVariable);

echo $theClass->theVariable;

Upvotes: 0

xil3
xil3

Reputation: 16449

You can do it 2 ways - see this example:

class bla {
  public static $yourVar;

  public function __construct($var) {
    self::yourVar = $var
  }
}

// you can set it like this without instantiating the class
bla::$yourVar = "lala";

// or pass it to the constructor while it's instantiating
$b = new bla("lala");

The first part you can only do with a static, but if you don't want to use a static, you'll have to initialize it via the constructor.

Hope that's what you were looking for...

Upvotes: 1

Luca Matteis
Luca Matteis

Reputation: 29267

$myVariable; // variable is defined

$myVariable = new myClass(); // instance of a class

Upvotes: 0

Mark Baker
Mark Baker

Reputation: 212522

If you mean instantiating the class, then use the constructor:

class Foo {

    private $_bar;

    public function __construct($value) {
        $this->_bar = $value;
    }

}

$test = new Foo('Mark');

Upvotes: 3

Related Questions