1

I'm new learner in PHP OOP, how can share or pass variable in between function within a class?

class Sample {

    public function One() {

         $var1 = 'abc';
         $var2 = 'xyz';

        return $var1;
    }

    public function Two() {

        $var3 = $var1.$var2;

        return $var3;
    }

}

Or is that possible to return multiple values?

thanks.

UPDATE

class Sample {

// This is how you declare class members
public $var1, $var2;

public function One() {

     // You use $this to refer class memebers
     $this->var1 = 'abc';
     $this->var2 = 'xyz';

    return $this->var1;
}

public function Two() {

    $var3 = $this->var1.$this->var2;

    return $var3;
}

}

$test = new Sample();
echo $test->Two();

I have test a provided example and it return blank in my page when calling function Two(), any idea?

1
  • If you don't call $test->One(), the variables remain unsetted. It's possible you may want to move the initialization to a constructor function (called __construct() in php)? Commented Dec 20, 2012 at 10:09

3 Answers 3

2

Make the variables public variables, declared after class Sample { and they can be used anywhere inside the class.

Sign up to request clarification or add additional context in comments.

3 Comments

They can be public, protected, private.
Yes, either and or. They can also be referenced by using $this->var1 etc
I can't see that by your post.
2

declare variables inside class and use $this to access variables

class Sample {
    public $var1;
    public $var2;

    public function One() {
        $this->var1 = 'abc';
        $this->var2 = 'xyz';
        return $this->var1;
    }

    public function Two() {
        $var3 = $this->var1.$this->var2;
        return $var3;
    }
}

1 Comment

Making things public is not a good solution. Class members should remain private until they are needed in a subclass (which means they should go to protected). Public members should be used when you build simple value-entities with no additional logic and a strong attitude towards performance. Otherwise use getter/setter methods for your private/protected members.
1
class Sample {

    // This is how you declare class members
    protected $var1, $var2;

    public function One() {

         // You use $this to refer class memebers
         $this->var1 = 'abc';
         $this->var2 = 'xyz';

        return $this->var1;
    }

    public function Two() {

        $var3 = $this->var1.$this->var2;

        return $var3;
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.