【问题标题】:How do I Create and Access PHP Object Variables如何创建和访问 PHP 对象变量
【发布时间】:2018-06-10 00:08:41
【问题描述】:

好的,所以我想通了 :) 多亏了您的示例,它现在应该如何工作。

class Test_Class { 
    public function Test_Function_1(array $Test_Array_1) {
        echo'TF1_Var_1 = '. $Test_Array_1['TF1_Var_1'] . '<br> <br>';
    }
    public function Test_Function_2($Test_Selector_2, array $Test_Array_2) {
        echo'Test_Selector_2 = '. $Test_Selector_2 . '<br>';
        echo'TF2_Var_1 = '. $Test_Array_2['TF2_Var_1'] . '<br>';
    }
}

$Test_Run = new Test_Class();
$Test_Run->Test_Function_1([ 'TF1_Var_1' => 'TF1_Val_1', 'TF1_Var_2' => 'TF1_Val_2', 'TF1_Var_3' => 'TF1_Val_3' ]);
$Test_Run->Test_Function_2('TF2_Selector_Data' , [ 'TF2_Var_1' => 'TF2_Val_1', 'TF2_Var_2' => 'TF2_Val_2', 'TF2_Var_3' => 'TF2_Val_3' ]);

我实际上没有意识到你可以将数组传递给函数,我以前没有遇到过这样的例子,所以我不知道这是可能的。 我以为你只能用逗号分隔字符串,所以谢谢。

【问题讨论】:

    标签: php object variables


    【解决方案1】:

    您可能应该阅读manual

    class TestClass { 
        public function test1(array $array) {
            var_dump($array);
        }
        public function test2($selector, array $array) {
            var_dump($selector, $array);
        }
    }
    
    $test = new TestClass();
    $test->test1([ 'TF1_Var_1' => 'TF1_Val_1', 'TF1_Var_2' => 'TF1_Val_2', 'TF1_Var_3' => 'TF1_Val_3' ]);
    $test->test2("TF2_Selector", [ 'TF1_Var_1' => 'TF1_Val_1', 'TF1_Var_2' => 'TF1_Val_2', 'TF1_Var_3' => 'TF1_Val_3' ]);
    

    【讨论】:

    • 我已经阅读了手册,但我从示例中学到了更好的东西。我不能从文档中真正理解 PHP 或任何语言。我将如何从该函数中访问这些设置变量?在“test1”或“test2”内。我是否必须将函数设为“静态”,以便将变量保留在函数内?
    • 天哪……你至少了解函数式编程的工作原理吗?你有使用任何语言的经验吗?
    • 您可能应该登录 udemy(即udemy.com/object-oriented-php-mvc)并观看一些视频以更好地了解其工作原理。无论如何 - 当您创建 classmethods 时,您可以在方法中要求 arguments。换句话说,函数test1 需要一个array 变量,然后将其存储在$array 中。在test1 中,您可以看到我正在使用var_dump($array),它将转储$array 变量的内容。 test2 函数也是如此。
    • 要在 php(或任何其他语言)中实例化 TestClass,您将使用 new TestClass 并将其用于变量 - 在这种情况下,变量是 $test。一旦你实例化了这个类,你就可以访问它的方法,如果它们是公共的——即$test-&gt;test2(argument1, argument2)。一旦您执行$test-&gt;test2(argument1,argument2),您实际上就是在执行该方法的代码块。这是一个非常非常快速的演练。您应该阅读 OOP(面向对象编程)和 MVC(模型视图控制器)
    猜你喜欢
    • 1970-01-01
    • 2019-04-15
    • 2015-05-22
    • 1970-01-01
    • 1970-01-01
    • 2021-01-24
    • 2019-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多