[英]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.