• 8

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191


File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

Extend PHP Class only if other class is defined

Some may argue that this could be bad practice due to potential inconsistencies, however, I am wondering how (if possible) I could tell a class to extend another class, but only if it's defined.

I'm aware this doesn't work, but what I'm effectively after is:

class MyClass extends (class_exists('OtherClass') ? OtherClass : null)

Or maybe a function that would run in the constructor to set up the extend if the class exists.

I of course want to avoid..

    class MyClass extends OtherClass
        //The class
    class MyClass
        //The class

.. because of the massive duplication of code.

I've looked for answers on Google and around the site, but found nothing - if I have duplicated a question however, do let me know.

You could create a middle-man class that's created inside the class_exists() condition, but without its own behavior:

if (class_exists('OtherClass')) {
    class MiddleManClass extends OtherClass { }
} else {
    class MiddleManClass { }

class MyClass extends MiddleManClass {
    // The class code here

This makes the class hierarchy include one more class, but has no duplicated code (has no code actually) and methods inside MyClass can reach the OtherClass with parent:: or $this as usual if it was available.

  • 15
Reply Report
      • 2
    • Yes of course! I was pseudo-coding something like this in my head, but couldn't fabricate anything useful. Cheers.
      • 2
    • Yesterday I saw the same code In the legacy code of one project in which I am working. Then I am wordering how Is the better way to do that operation. I think that there are several solutions respecting the standard of PHP. Also, I am not able to see the problems that this solutions could causes, for example: autoload, apc, etc. Thanks.

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions