English 中文(简体)
Require a method in parent class to be called in PHP
原标题:

As the title states, I m trying to make a method in a parent class required. Although, I suppose it could be any class. For instance:

class Parent
   {
      function foo ()
        {
           // do stuff
        }
   }

  class Child extends Parent
    {
       function bar ()
        {
           // do stuff after foo() has ran
        }
    }

Basically, I want foo() to be required to run or Child class doesn t run and returns an error or redirects to a different page. I could call the function, but I m wondering If I can make it a requirement when extending the parent class.

问题回答

If you leverage abstract classes and methods, you can force subclasses to implement the missing methods.

abstract class ParentClass
{
  public function foo ()
  {
    // do stuff
    $this->bar();
  }

  abstract protected function bar();
}

class Child extends ParentClass
{
  protected function bar()
  {
    // does stuff
  }
}

Subclasses that don t implement bar() will generate a fatal error.

What you should probably do is override Parent::foo() and then call the parent method in the overridden method like so:

class Parent
{
  function foo ()
    {
       // do stuff
    }
}

class Child extends Parent
{
   function foo ()
    {
       if(!parent::foo()) {
            throw new Exception( Foo failed );
       }

       // do child class stuff
    }
}

Why not just set a boolean in function foo() that acts as a flag. Check to see if it has been set in the child class/functions, and you re all set.

Have the child call the function from the parent in the construct.

class Child extends Parent
{
   function bar ()
    {
       // do stuff after foo() has ran
    }
    function __construct(){
         parent::foo();
    }
}

As already mentioned, it sounds like you want foo() to be abstract, forcing child classes to override it.

Any class containing an abstract class in PHP requires your parent class to be abstract too. This means it can t be instantiated (constructed), only derived / sub-classed. If you try to instantiate an abstract class the compiler will issue a fatal error.

http://php.net/manual/en/language.oop5.abstract.php

See the code in Peter Bailey s answer.

If you re not actually initializing any code within parent class you should use an object interface. Interface methods have to be implemented or the script will throw a fetal error.

More information on them can be found: http://us3.php.net/interface.

I think this might be the only way of implementing such functionality, as I don t think there is a built in solution.

class Parent
{
    public $foo_accessed = FALSE;
    function foo ()
    {
       $this->foo_accessed=TRUE;
       // do stuff
    }
}

class Child extends Parent
{
   function bar ()
    {
       if($this->foo_accessed==TRUE) {
           // do stuff after foo() has ran
       } else {
           // throw an error
       }
    }
}

Do not depend on other methods. Make sure they ve ran.

class Parent
{
    function foo()
   {
       // do stuff
   }
}

class Child extends Parent
{
    private function bar()
   {
       // do child class stuff
   }

   public function doFooBar()
   {
    parent::foo();
    $this->bar();
   }

}

Following approach will only ever complain after all processing has been done - however if that is fair to you it will definately make sure foo() has been called in the parent class or otherwise trigger a condition that you can act upon.

class DemandingParent { 

    private $hasFooBeenCalled = false;

    public function foo() {
        $this->hasFooBeenCalled = true;

        /* do Stuff */
    }

    public function __destruct() {
        if (!$this->hasFooBeenCalled) {
            throw new Exception("Naughty Child! Call your parent s foo b4 you speak up!");
        }
    }
}




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签