[英]Access a variable nested in a function inside a class in php
這是我的代碼的簡化版本,其中包含主class
和主function
我需要獲取用戶輸入的'userName'
值,才能在'mainFunction'
使用它,嘗試將'myForm'
內部的'userName'
'myForm'
全局,但沒有得到值。
可以在'userName'
'mainClass'
使用'userName'
值,以便在任何地方使用它?
class mainClass {
function myForm() {
echo '<input type="text" value="'.$userName.'" />';
}
}
function mainFunction () {
$myArray = array (
'child_of' => $GLOBALS['userName']
)
}
class mainClass {
public $username;
function __construct($username){
$this->username = $username;
}
function myForm() {
echo '<input type="text" value="'.$this->userName.'" />';
}
}
function mainFunction () {
$myArray = array (
'child_of' => $this->username;
);
}
可以在'mainClass'之外使用'userName'的值,以便在任何地方使用它?
是。
首先,您需要定義一個這樣的類屬性
class MainClass
{
private $_userName;
public function myForm()
{
echo '<input type="text" value="'.$this->_userName.'" />';
}
}
查看如何在myForm()方法內訪問此屬性。
然后,您需要為此屬性定義getter方法(或可以將該屬性公開),如下所示:
class MainClass
{
private $_userName;
public function getUserName()
{
return $this->_userName;
}
public function myForm()
{
echo '<input type="text" value="'.$this->_userName.'" />';
}
}
您可以像這樣訪問用戶名屬性
$main = new MainClass();
$userName = $main->getUserName();
請注意,您需要MainClass類的實例。
我建議您從簡單的概念入手,並確保您100%理解這一點。 我也建議避免將全局變量和更復雜的邏輯與靜態方法一起使用。 嘗試使其盡可能簡單。
熱烈的問候,維克多
下面的代碼是一個非常最小化版本笨 get_instance方法。 因此,在您的情況下,您可以在此代碼的開頭:
/** Basic Classes to load the logic and do the magic */
class mainInstance {
private static $instance;
public function __construct()
{
self::$instance =& $this;
}
public static function &get_instance()
{
return self::$instance;
}
}
function &get_instance()
{
return mainInstance::get_instance();
}
new mainInstance();
/** ----------------------------------------------- */
然后您可以像這樣創建全局類:
class customClass1 {
public $userName = '';
function myForm() {
return '<input type="text" value="'.$this->userName.'" />';
}
}
/** This is now loading globally */
$test = &get_instance();
//If you choose to actually create an object at this instance, you can call it globally later
$test->my_test = new customClass1();
$test->my_test->userName = "johnny";
/** The below code can be wherever in your project now (it is globally) */
$test2 = &get_instance();
echo $test2->my_test->myForm()."<br/>"; //This will print: <input type="text" value="johnny" />
echo $test2->my_test->userName; //This will printing: johnny
由於這現在是全局的,因此您甚至可以像下面這樣創建自己的函數:
function mainFunction () {
$tmp = &get_instance();
return $tmp->my_test->userName;
}
echo mainFunction();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.