UndefinedReference
UndefinedReference

Reputation: 1253

Passing Variables Between Two Classes

I have two classes that implement the same interface.

In class one I have an array variable called author. Typically to pass variables between two different functions in the same class I use $this->author; once it's been set.

This doesn't seem to work between two classes. Can someone please clarify how I would call a variable from class one in class two?

Thanks!

Upvotes: 0

Views: 2497

Answers (2)

Antonycx
Antonycx

Reputation: 269

You can use Traits (horizontal inheritance) http://php.net/manual/es/language.oop5.traits.php

Although it will only help you if your variable will only be consulted and not to be modified. Thats because, traits allow you to specify static properties, but each class using that trait has independent instances of those properties.

http://php.net/manual/es/language.oop5.traits.php#107965

This is an example:

trait myTrait {
  public $sameVariable = 'shared';

    public function getMessage() { 
        echo $this->sameVariable;
    }
}

class A {
    use myTrait;
    public function getMessageA() { 
        echo $this->sameVariable;           //Prints shared
        $this->sameVariable = 'changed';
        echo $this->sameVariable;           //prints changed
    }
}


class B {
    use myTrait;
    public function getMessageB() { 
        echo $this->sameVariable;           //Prints shared
    }
}

$a = new A();
$b = new B();

$a->getMessageA();
$b->getMessageB();

This permits you reuse the variable having it in a Trait instead of duplicate your code, but i don't understand your case so well. So that maybe this is not what you want =/

Upvotes: 1

RichColours
RichColours

Reputation: 670

http://php.net/manual/en/language.oop5.php for nomanclature of object-oriented design concepts.

When you use $this->author you are not passing variables between functions. The two functions are referencing the same variable of the object that both the functions belong to.

author is a property of the class.

There is no place that you could put a variable and have it referenced by two different classes. However, you could use a public property on one class and reference that from any other class.

http://php.net/manual/en/language.oop5.visibility.php for public properties.

But that technique doesn't capture the scheme you have with two functions referencing a common property.

Upvotes: 1

Related Questions