簡體   English   中英

如何在創建類之前定義變量?

[英]How can I define a variable before create the class?

如何在初始化類之前或初始化時定義變量?

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

如果您的意思是實例化該類,那么使用構造函數:

class Foo {

    private $_bar;

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

}

$test = new Foo('Mark');

您可以通過兩種方式完成 - 請參閱此示例:

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

第一部分只能用靜態做,但如果你不想使用靜態,你必須通過構造函數初始化它。

希望這就是你要找的......

$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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM