如何在方法之间共享行为

时间:2014-06-26 16:37:34

标签: php oop

我有一组getter / setter方法与我的类属性进行交互,这里有两个相似的方法:

public function Criteres ($name = '',$value = false)
 {if ($name == '') return $this->Criteres;
  else if ($value !== false && strlen($name)) $this->Criteres[$name] = $value;
  else if (strlen($name)) return (isset($this->Criteres[$name]) ? $this->Criteres[$name] : '');}

public function Navigation ($name = '',$value = false)
 {if ($name == '') return $this->Navigation;
  else if ($value !== false && strlen($name)) $this->Navigation[$name] = $value;
  else if (strlen($name)) return (isset($this->Navigation[$name]) ? $this->Navigation[$name] : '');}

他们有完全相同的行为,唯一的变化是他们行动的财产。我应该提一下,被访问的属性实际上是包含多个属性的数组

有没有办法让它们扩展成一种抽象的方法,它会使它们的行为相同,而不是每次都定义行?

或任何其他方式延伸,我真的不在乎。

例如,我想要的结果是这样的:

PS。我知道这不是我们如何使用抽象类, abstract 会是某种关键字来帮助php理解定义的类是模板

abstract function setterGetter ($name = '',$value = false)
 {if ($name == '') return $this->{PROP};
  else if ($value !== false && strlen($name)) $this->{PROP}[$name] = $value;
  else if (strlen($name)) return (isset($this->{PROP}[$name]) ? $this->{PROP}[$name] : '');}

然后,为属性定义自定义setter / getter:

public function Criteres extends setterGetter ({Criteres})
 {}
public function Navigation extends setterGetter ({Navigation})
 {} // without the need to define the code, they all act the same

1 个答案:

答案 0 :(得分:3)

您不能扩展方法也不能使用由具有不同名称的两种不同方法实现的抽象方法。在所有抽象类和接口都应该提供一种解决函数的独特方法之后。

但如果CriteresNavigation都是同一个类的方法/成员,则可以为这些引用的对象编写一个通用的setter / getter。例如:

class MyData {

    protected $criteres;
    protected $navigation;

    public function objectHelper( $type, $name = null, $value = null )
    {
        $possibleTypes = array( 'Criteres', 'Navigation' );

        if( !in_array( $type, $possibleTypes ) )
        {
            throw new InvalidArgumentException( 'There is no such child object as ' . $type );
        }

        $type = strtolower( $type );

        if( empty( $name ) )
        {
            // getter
            return $this->$type;
        }
        elseif( !empty( $value ) )
        {
            /* setter
             * Attention: there no check at this point whether the key $name exists. */
            $this->$type[$name] = $value;
        }
        elseif( isset( $this->$type[$name] ) )
        {
            // specific getter
            return $this->$type[$name];
        }
        else
        {
            return null;
        }
    }

    /**
     * PHP magic function to use direct name notation
     *
     * Example:
     * 
     *   $myData->Navigation( 'name', 'value' );
     */
    public function __call( $prop, $args )
    {
        return $this->objectHelper(
            $prop,
            isset( $args[0] ) ? $args[0] : null,
            isset( $args[1] ) ? $args[1] : null
        );
    }

}

提示:在PHP中,通常使用null作为不需要的函数参数。

我会尽量避免混合使用者和吸气剂。您的代码将更具可读性,可测试性并且可能具有更高的性能。