php oo programming parent to instantiate child

Possible Duplicate:
What exactly is late-static binding in PHP?

I would like to build an abstract class that will instantiate it's child class using a static function.

<?php

class A
{
    protected $value;

    public function __construct($value)
    {
        $this->value = $value;
    }

    public static function create($value)
    {
        /* A must not know about B! 
         * I give that example for the context understanding */
        return **new B**($value);
    }
}

class B extends A
{
}

Of course A has not to know about B.. I do not know if it is possible and I do not want to have to implement the create function in all my 170 subclasses...

Do you think I should use a Factory that would return the instance of one of my 170 classes? That is cumbersome and not very maintainable..


I found out a solution, but is it ok?

<?php

class A
{
    protected $value;

    public function __construct($value)
    {
        $this->value = $value;
    }

    public static function create($value)
    {
        $child = get_called_class();
        return new $child($value);
    }
}

I tested it, it's working OK it's really useful in my context.. I do not know if it's ugly, because the parent class doesn't know about the child class, and if the Child class does not exists, the caller will not be allowed to call the create function..

Now, for my practical test, I use:

$graph->setBgcolor(Bgcolor::create('yellow')->valid());

with

 public function setBgcolor(Bgcolor $bgcolor)

A successful implementation could be like this

class A
{
    protected $value;
public static function create($value)
{
    $type = "NotDivisible";
    for ($i = 2; $i <= 10; $i++) {
         if($value % $i == 0)
         {
             $type = "DivisibleBy".$i;
             break;
         }
    }
    $instance = new $type;
    $instance->value = $value;
    return $instance;
}
}

public class DivisibleBy2 extends A
{
} 

public class DivisibleBy3 extends A
{
} 

public class DivisibleBy5 extends A
{
} 
...

so on.... (I haven't compiled it, sorry for syntax error)

Now as you know static method has nothing to do with the instance of object created because this is why we create a static method at the first place.

So you can put them in any other class and congrats you have implemented the factory design pattern.

However this is not a good implementation.


Another solution would NOT to use the static function and use basic new...

<?php

class A
{
    protected $value;

    public function __construct($value)
    {
        $this->value = $value;
    }
}

Now, for my practical test, I use:

$graph->setBgcolor(new Bgcolor('yellow'));

with

 public function setBgcolor(Bgcolor $bgcolor)

I still think that

Bgcolor::create('yellow')->foo()

looks better than

(new Bgcolor('yellow'))->foo()
链接地址: http://www.djcxy.com/p/58034.html

上一篇: 单身人士PHP后期静态绑定

下一篇: PHP的oo编程父母来实例化孩子