如果我有一個文件class.php
:如何從一個方法中得到一個變量的
class Greeting {
function Hello {
$variable = 'Hello World!';
}
}
然後一主文件index.php
:
include('class.php');
$page = new Greeting();
$page->Hello();
我如何可以訪問內部的$variable
內容index.php
?
如果我有一個文件class.php
:如何從一個方法中得到一個變量的
class Greeting {
function Hello {
$variable = 'Hello World!';
}
}
然後一主文件index.php
:
include('class.php');
$page = new Greeting();
$page->Hello();
我如何可以訪問內部的$variable
內容index.php
?
你無法像現在這樣訪問它。你需要做一個屬性,如:
class Greeting {
public $variable = 'Hello World!';
function Hello {
return $this->variable;
}
}
然後你就可以訪問它想:
$page = new Greeting();
echo $page->variable;
// or
echo $page->Hello();
取而代之,將$variable
公開在類中,然後將其設置在Hello()函數中。
class Greeting {
public $variable = '';
function Hello {
$this->variable = 'Hello World!';
}
}
然後,你可以通過做檢索:
include('class.php');
$page = new Greeting();
$page->Hello();
echo $page->variable;
另一種辦法是讓你好()返回$變量,然後你可以從那裏取回。
只是爲了不要忽視所有的可能性,你也可以這樣做:
class Greeting {
function Hello() {
global $variable;
$variable = 'Hello World!';
}
}
$page = new Greeting();
$page->Hello();
echo $variable;
但不要這樣做!這個不成立。
class Greeting {
public $variable = 'Hello World!';
function Hello(){
echo $this->variable;
}
}
$page = new Greeting();
$page->Hello();