tags:

views:

160

answers:

3

Is there a way to set something as global in a class and have all methods of that class to have access to it? Currently if I use global $session; I have to add it into every method that uses it even if all the methods are in the same class.

If I try to add it directly into the class then I get a php error saying it is expecting a function

global $session;

Here is a better example...

class test{
    function test1(){
     $self->test2($var);
    }

    function test2($var){
     return $var
    }
}

in this case I am getting this error below, do I need to use global or what? Fatal error: Call to a member function test2() on a non-object

+3  A: 

I may be misunderstanding the question, but I think what you want is an instance variable:

<?php
    class Foo {
        var $bar = "blue"

        function output() {
            echo $this->bar . "\n";
        }

        function a() {
            $this->bar = "green";
        }
        function b() {
            $this->bar = "red";
        }
    }
 ?>

In this case, $bar is the instance variable, accessible from each method. The following code, using the Foo class:

$newFoo = new Foo();
$newFoo->output();
$newFoo->a();
$newFoo->output();
$newFoo->b();
$newFoo->output();

Would create the following output:

blue
green
red
Doug Hays
sorry I kind of had 2 questions that got mixed together here, what I meant is lets say I have 2 methods in 1 class, I need to call method b inside of method a but I get this error when I do Fatal error: Call to a member function test2() on a non-object
jasondavis
Are you calling $this->test2(); ?
Doug Hays
+2  A: 

You're getting an error because you're using "self" instead of "this".

i.e. $this->test2($var);

mfabish
thanks that saved me a lot of time
jasondavis
+3  A: 

There are different ways to do this,

<?php
class test{
    private $p_var;
    public static $s_var;

    function  test(){
        $this->p_var="RED";
        self::$s_var="S_RED";
    }

    function test1(){
        return $this->test2($this->p_var);
    }
    function test2($var){ 
        return $var;
    }
    function test3($var){ 
        $this->p_var=$var;
    }

    function stest1(){
        return $this->test2(self::$s_var);
    }
    function stest2($var){ 
        return $var;
    }
    function stest3($var){ 
        self::$s_var=$var;
    }

} 
?>

Heere $objtest is the object of the test() class:

$objtest=new test();

echo  $objtest->test1(),"<br/>"; 
$objtest->test3("GREEN"); 
echo $objtest->test1(),"<br/>";
echo "<br/>";

echo  $objtest->stest1(),"<br/>"; 
$objtest->stest3("S_GREEN"); 
echo $objtest->stest1(),"<br/>";

test::$s_var="S_BLUE";
echo $objtest->stest1();

Would create the following output

RED
GREEN

S_RED
S_GREEN
S_BLUE

Using static variable(test::$s_var) you can achieve what you want. If you have any confusion about self and $this then you can read this document

Imrul