0

Basically, I want to use a key and be able to call a function in a class from another class.

Maybe the example I will provide will give a better explanation as to what I mean. I thought of const but I would not be able to modify it from there.

I thought about parsing the key as a constructor, I was just wondering if there is any other better way of doing it since it'll be used in multiple classes.

Class1.php

<?PHP

class Class1 {
    public $key;

    public function setKey($k)
    {
        $this->key = $k;
    }

    public static function getKey()
    {
        return $this->key; // this won't work because static
    }
}


?>

Class2.php

<?PHP

class Class2 {
    public function __construct()
    {
        echo Class1::GetKey(); // Need to retrieve the key here
    }
}
?>

index.php

<?PHP

require_once("Class1.php");
require_once("Class2.php");

$c1 = new Class1();
$c1->setKey("thekey");


$c2 = new Class2();
?>
Nathan
  • 534
  • 1
  • 5
  • 13

3 Answers3

1

One way to achieve this is by turning the class storing common data into a singleton. Essentially you just add a way to consistently return the same instance of the class:

class MyClass
{
    /**
     * @var MyClass
     */
    protected static $instance;

    protected $key;

    public static getInstance()
    {
        if (!self::$instance) {
            self::$instance = new MyClass();
        }

        return self::$instance;
    }

    public function setKey($k)
    {
        $this->key = $k;
    }

    public static function getKey()
    {
        return $this->key;
    }
}

Then use it like this:

// Both of these use the same instance of MyClass
MyClass::getInstance()->setKey('hello');
MyClass::getInstance()->getKey();

This allows you to write the class using instance properties and methods, without making everything static.

Further reading:

Community
  • 1
  • 1
Stecman
  • 2,890
  • 20
  • 18
0

You can use a static property, this way you can use it outside of the class and it can be changed later. For example:

class Class1
{
    static $key = 'ABC';
}

class Class2
{
    public function __construct()
    {
        echo 'Original key: ' . Class1::$key . '<br />';

        Class1::$key = '123';

        echo 'New key: ' . Class1::$key;
    }
}

new Class2();

Prints:

Original key: ABC
New key: 123

But to keep the encapsulation concept, i suggest you to try to use get and set methods.

Marcio Mazzucato
  • 8,841
  • 9
  • 64
  • 79
0

Make your class2 like this

<?PHP

class Class2 {
 public function __construct(Class1 $a1)
 {
    echo $a1->GetKey(); // Need to retrieve the key here
 }
}
?>  

and make index.php like this ways

<?PHP

require_once("Class1.php");
require_once("Class2.php");

$c1 = new Class1();
$c1->setKey("thekey");


$c2 = new Class2($c1);

?>

Shaiful Islam
  • 7,034
  • 12
  • 38
  • 58