Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending PHP classes

Tags:

php

class

extends

I'm still learning how to use classes and I was wondering when should I use the extends keyword (extend a class).

Let's say I have a class that does thing A (and it's a singleton). Is it ok to extend it to another one that does thing B, even if class B is not really related to class A, but it uses a lot of its methods? Or should I create a new class?

like image 861
Alex Avatar asked Jun 12 '26 13:06

Alex


1 Answers

When it comes to Object-Oriented programming generally a class does a specific task, such as hold user information, or input / output control.

When you have let's say 1 object that is used to control the output, you can set a method within that object to control the output type, or how a each specific content should be handled, but that would mean that the objects sole purpose has been broken, as it's now not just sending content, but it's also manipulating content depending on it's type.

A way in which we use to over come this is by grouping a set of tasks into a group of classes / objects, example:

abstract class Output
{
    public $content_type = 'text/plain';

    public function _send(){}
}

The output class would obviously have much more methods but only methods related to ouputting content, such as headers etc, and not the manipulation of the content, then you would have something like:

class HTMLOutput extends Output
{
     public $content_type = 'text/html';
}

and for the manipulation of the content:

class CSSOutput extends Output
{
    public $content_type = 'text/css';

    public _send()
    {
         if($_SERVER['APP']['Settings']['CSSCompress'] == '1')
         {
             $this->_compress_css();
         }

         parent::_send();
    }

    private function _compress_css()
    {
         $this->content = ; //Some compression lib
    }
}

This is the main architecture points that I abide by when creating and organizing many grouped classes / objects.

like image 50
RobertPitt Avatar answered Jun 15 '26 02:06

RobertPitt