Jump to content


Photo

using functions unsets variables...


  • Please log in to reply
2 replies to this topic

#1 newb

newb
  • Members
  • PipPipPip
  • Advanced Member
  • 454 posts

Posted 08 October 2006 - 04:40 AM

eh how come this happens...

the code doesn't echo what variable 'a' is set to..why?...
<?php
class variable {
function loadvars() {
$a = 'lol';
}

function newfunction() {
$this->loadvars();
echo $a;
}
}

$variable = new variable();
$variable->newfunction();
?>


#2 AliasXNeo

AliasXNeo
  • Members
  • PipPip
  • Member
  • 11 posts

Posted 08 October 2006 - 05:10 AM

What did you expect to happen? You must be new to classes. In a function, variables that are not set with global are completely local to the function. So if you made a function that set some random variable, then made another that printed that variable out, it wouldn't work because the random variable you made was only local to the first function, and not the second. Now, in classes you can create variables that are local to the class, which would also make them local to all the functions inside that class. Here is an example:

<?php
class test {
    var $testing = "";
    function set_test()
    {
        $this->testing = "testing"; // Set's our local variable $testing to "testing"
    }
    function echo_test()
    {
        echo($this->testing); // Echo's our local variable testing
    }
}

$class = new test();
$class->set_test(); // Set's our $testing variable to "testing"
$class->echo_test(); // Displays "testing"
?>

As you see we simply reference our local class variable using $this, as you would reference a local function. Did that clear things up?

#3 newb

newb
  • Members
  • PipPipPip
  • Advanced Member
  • 454 posts

Posted 08 October 2006 - 05:23 AM

Ohh ok, thanks alot. and yes, im new to functions and classes so that helped a bunch




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users