Jump to content

using functions unsets variables...


newb

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]
Link to comment
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?
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.