访问嵌套在php中类中的函数中的变量

时间:2013-03-03 09:53:57

标签: php

以下是我的代码的缩减版本,主要class和主function

我需要获取用户输入的'userName'的值,以便在'mainFunction'中使用它,尝试在'userName''myForm'全局但不是得到价值。

可以在'userName'旁边找到'mainClass'的值,以便我可以在任何地方使用它吗?

 class mainClass {

  function myForm() {
      echo '<input type="text" value="'.$userName.'" />';
   }

 }   
 function mainFunction () {
    $myArray = array (

         'child_of' => $GLOBALS['userName']

      ) 
 }

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

  

'userName'的值是否可以在'mainClass'旁边使用,以便我可以在任何地方使用它?

首先,您需要定义一个类属性

class MainClass
{

    private $_userName;

    public function myForm()
    {
        echo '<input type="text" value="'.$this->_userName.'" />';
    }
}

看看你如何在myForm()方法中访问这个属性。

然后你需要为这个属性定义getter方法(或者你可以将属性设为public),如下所示:

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%理解这一点。另外我建议使用静态方法避免使用全局变量和更复杂的逻辑。尽量使它尽可能简单。

热烈的问候, 维克多

答案 2 :(得分:-1)

以下代码是Codeigniter 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();