Micah
Micah

Reputation: 4550

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(); But in PHP seem like this way will not work.

Please advice a way that can read $this-A inside of C() without give function variable.

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

However,if global, the global here means the entire script not within the class.

Thank you very much for your advice.

Upvotes: 0

Views: 209

Answers (2)

Dave
Dave

Reputation: 3288

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

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

Upvotes: 1

Sven
Sven

Reputation: 70863

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".

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.

Upvotes: 1

Related Questions