Jump to content

Archived

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

newb

using functions unsets variables...

Recommended Posts

eh how come this happens...

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

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

$variable = new variable();
$variable->newfunction();
?>[/code]

Share this post


Link to post
Share on other sites
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:

[code]<?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"
?>[/code]

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

Share this post


Link to post
Share on other sites
Ohh ok, thanks alot. and yes, im new to functions and classes so that helped a bunch

Share this post


Link to post
Share on other sites

×

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.