简体   繁体   中英

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";
?>

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

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

$myVariable; // variable is defined

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

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


$theVariable = 'The Value';

$theClass = new myClass($theVariable);

echo $theClass->theVariable;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM