Jump to content

Quick question about variable scope


hadoob024

Recommended Posts

I'm having a complete brainfart right now and can't seem to remember this.  Tried looking it up in the manual, but couldn't find an example.  Here's what I have:

 

class myclass {

    function testA {
        

    }

    function testB {

    }
}

 

 

So that's my basic setup.  I want to define a variable.  I then want to set it's value in testA().  I then want to be able to access the value in testB().  Where and how do I define this variable?

 

I thought all I had to do was something like:

 

class myclass {

    public $tempvar='';
    
    function testA {
        $tempvar="my new value";

    }

    function testB {
        echo $tempvar;

    }
}

 

But this says that $tempvar is equal to NULL.  What am I forgetting?  Thanks in advance!

Link to comment
https://forums.phpfreaks.com/topic/226728-quick-question-about-variable-scope/
Share on other sites

This should do it:

 

<?php
class myclass {

    public $tempvar='';
    
    public function testA() {
        $this->tempvar="my new value";
    }

    public function testB() {
        echo $this->tempvar;
    }
}

$class = new myclass;
$class->testA();
$class->testB();

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.