keepwalking
keepwalking

Reputation: 2654

PHP Class Parent Instance (Singleton)

The scenario is this

class a
{
  public $val;
}

class b extends a
{

}

class c extends b
{

}

$one = new b();
$one->val = "a value";

$other = new c();

echo $other->val;
// wanted 'a value', got ''

So the result i need here is: "a value", but of course is blank.

What i need is that the 'a' class to always be used as an instance in 'b'. So whenever i use a class that extends the 'b', the parent 'a' class to be inhereted as an instance.

Upvotes: 0

Views: 891

Answers (3)

Gordon
Gordon

Reputation: 316969

Here is how to do it without Inheritance:

class A
{
    public $foo;
}
class B {
    public function __construct(A $a)
    {
        $this->a = $a;
    }
}
class C {
    public function __construct(A $a)
    {
        $this->a = $a;
    }
}

$a = new A;
$b = new B($a);
$c = new C($a);
$b->a->val = 'one value';
echo $c->a->val;

If you dont like having to fetch $a first to get to val, you could assign by reference

class A
{
    public $foo;
}
class B {
    public function __construct(A $a)
    {
        $this->val = &$a->val;
    }
}
class C {
    public function __construct(A $a)
    {
        $this->val = &$a->val;
    }
}

$a = new A;
$b = new B($a);
$c = new C($a);
$b->val = 'one value';
echo $c->val;

Though personally I find the first approach more maintainable and clear.

Upvotes: 1

regality
regality

Reputation: 6554

If you read the php manual on the static keyword it gives an example of exactly what you are trying to do. You can read about it here: http://www.php.net/manual/en/language.oop5.static.php

Here is the example code they use.

<?php
class Foo
{
    public static $my_static = 'foo';

    public function staticValue() {
        return self::$my_static;
    }
}

class Bar extends Foo
{
    public function fooStatic() {
        return parent::$my_static;
    }
}


print Foo::$my_static . "\n";

$foo = new Foo();
print $foo->staticValue() . "\n";
print $foo->my_static . "\n";      // Undefined "Property" my_static 

print $foo::$my_static . "\n";
$classname = 'Foo';
print $classname::$my_static . "\n"; // As of PHP 5.3.0

print Bar::$my_static . "\n";
$bar = new Bar();
print $bar->fooStatic() . "\n";
?>

Upvotes: 1

fatnjazzy
fatnjazzy

Reputation: 6152

Since $other = new c(); is actually creating a new instance, it is not possible.
but if you declare val as Static member, you will have the result that you want.

    <?
class a
{
  public static $val;
}

class b extends a
{

}

class c extends b
{

}

$one = new b();
a::$val = "a value";



echo c::$val;

Upvotes: 1

Related Questions