tags:

views:

59

answers:

4

Hi
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";
?>
+3  A: 

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');
Mark Baker
A: 
$myVariable; // variable is defined

$myVariable = new myClass(); // instance of a class
Luca Matteis
How did this get a vote? Makes me wonder sometimes if people just have a bunch of friends standing by to vote for all their answers, even if they're not helpful at all...
xil3
@xil3, i actually answered his initial weird question, but then he edited it... it's still weird.
Luca Matteis
+1  A: 

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...

xil3
A: 
class myClass {
    protected $theVariable;

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


$theVariable = 'The Value';

$theClass = new myClass($theVariable);

echo $theClass->theVariable;
Joseph