如何在初始化类之前或初始化时定义变量?
<?php
class class{
public $var;
public function __construct(){
echo $this -> var;
}
}
$class = new class;
$class -> var = "var";
?>
答案 0 :(得分:3)
如果你的意思是实例化类,那么使用构造函数:
class Foo {
private $_bar;
public function __construct($value) {
$this->_bar = $value;
}
}
$test = new Foo('Mark');
答案 1 :(得分:1)
你可以采取两种方式 - 见这个例子:
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");
第一部分只能用静态做,但如果你不想使用静态,你必须通过构造函数初始化它。
希望这就是你要找的......
答案 2 :(得分:0)
$myVariable; // variable is defined
$myVariable = new myClass(); // instance of a class
答案 3 :(得分:0)
class myClass {
protected $theVariable;
protected function myClass($value) {
$this->$theVariable = $value;
}
}
$theVariable = 'The Value';
$theClass = new myClass($theVariable);
echo $theClass->theVariable;