使用父方法访问子类变量

时间:2018-01-11 19:01:17

标签: php oop

我有一个Authorize超类和一个Webhook_Authorize子类。子类包含该类授权的唯一方法和变量的所有内容,而超类包含我的所有一般授权方法。以下代码段中的示例:

class Authorize{

    public static function is_authorized( $auth_code_input ){

        $is_authorized = static::$authorization === $auth_code_input ? true : false;

        return $is_authorized;

    }

}

class Webhook_Authorize extends Authorize{

    protected static $authorization = 'test823475290345876';

}

我想在另一个文件中调用它:

if ( Webhook_Authorize::is_authorized( 'test823475290345876' ) ) {

    http_response_code(403);

    echo '<h1>403 | Forbidden</h1>';

    exit;

}

如何使用此配置执行此操作?我是OOP的新手,我做了一些修改来解决这个问题,但这对我来说真的只是一个黑暗的镜头。

2 个答案:

答案 0 :(得分:1)

这是糟糕的OOP练习。如果父类依赖于子类中的数据,则不能直接使用它。您尝试解决的问题最好由您的类Authorize定义为一个抽象类来处理,该类需要子类来定义设置授权代码的方法。然后将authorization_code()返回值传递给父类中的is_authorized方法。

对于所需的结果,您还必须在调用!方法的if条件下使用Webhook_Authorize::is_authorized运算符。

请参阅下面的完整工作示例:

<?php

abstract class Authorize
{

    abstract protected function authorization_code();

    public static function is_authorized($auth_code_input)
    {
        $auth = new static();
        return $auth->authorization_code() === $auth_code_input;
    }

}

class Webhook_Authorize extends Authorize
{

    protected function authorization_code()
    {
        return 'test823475290345876';
    }

}

if ( ! Webhook_Authorize::is_authorized( 'test823475290345876' ) ) {

    http_response_code(403);

    echo '<h1>403 | Forbidden</h1>';

    exit;

}

答案 1 :(得分:-1)

可以通过Dependency Injection在PHP中完成。

class ExParent{
             private ExChil $exChild;
             public __construct($child){
                $this->exChild = $child;
             }
             public static function getChildVariable(){
              return $this->exChild->getVariable();
             }
}

class ExChild extends ExParent{
         private $variable;
         public function setVariable($value){
           $this->variable = $value;
         }
         public function getVariable($value){
           return $this->variable;
         }
}

       //define the variable on child
       $child = new ExChild();
       $parent = new ExParent($child);
       $child->setVariable('something');
       //access the variable from parent
       var_dump($parent->getChildVariable());
相关问题