简体   繁体   English

PHP函数内部的外部函数的PHP调用变量

[英]PHP call variable of outside function from inside functon

I have a question how to call a variable. 我有一个问题如何调用变量。

In Js, if I write $A = $this->A inside of B() , I could reach $this->A through $A inside of C() ; 在Js中,如果我在B()内部写入$A = $this->A ,则可以通过C()内部的$A达到$this->A But in PHP seem like this way will not work. 但是在PHP中,这种方式似乎行不通。

Please advice a way that can read $this-A inside of C() without give function variable. 请提出一种无需给定函数变量就可以读取C()中的$ this-A的方法。

class X {

    function B(){
        function C(){
           $this->A;  // Can not call A here
           $A; // No work either

        }
        $A = $this->A; // 

        $this->A; // Can call A here
    }

    private $A;
}

This one here is Global $A Get variables from the outside, inside a function in PHP 这是Global $A 在PHP函数内部从外部获取变量

However,if global, the global here means the entire script not within the class. 但是,如果为全局,则此处的全局表示整个脚本不在类中。

Thank you very much for your advice. 非常感谢您的建议。

You cannot define functions within functions, avoid it, it is bad! 您不能在函数中定义函数,要避免它,这是不好的! The function will not be restricted to the scope. 该功能将不限于范围。 Functions are always global. 功能始终是全局的。

Although it will work on the first run, the execution of such code will only define the function then (it will be unavailable for calls before), and on the next call will crash with "redefined function error". 尽管它将在第一次运行时起作用,但是此类代码的执行只会在之后定义函数(之前的调用将无法使用),并且在下一次调用时将崩溃并显示“ redefined function error”。

Knowing this, what your code does is define a global function "C" that is actually outside the class, and thus has no access to private properties. 知道这一点,您的代码将定义一个实际上在类外部的全局函数“ C”,因此无法访问私有属性。

As Sven said function within a function is bad however ignoring that you can also do this to expose non functional scope vars to within the function 正如Sven所说,函数内的函数很糟糕,但是忽略了您也可以这样做,以将非函数范围var暴露给函数

class X {

    function B(){
        $A = $this->A; //
        function C(){
           global $A; // No work either
        }
        $this->A; // Can call A here
    }

    private $A;
}

EDIT from the comment: 从评论中编辑:

class X { 

    public $inputvar; 
    public $outputvar; 

    public function B($changeinput) { 
        $this->inputvar = $changeinput; 
    } 

    public function C($secondinput) { 
        $this->outputvar = $this->inputvar." == ".$secondinput; 
    } 

    public function return_var() { 
        return $this->outputvar; 
    }
}

$testclass = new X(); 

$testclass->B("test input"); 
$testclass->C("second input"); 
$testclass->inputvar = "BLAAH"; 

echo $testclass->return_var();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM