user701510
user701510

Reputation: 5763

Is it bad practice to include classes within classes?

Let's say I have a class file called smallBox.php:

<?php
class SmallBox {

    public function boxMethod() {}

}

I then include the smallBox.php file into another class using 'require':

<?php
class BigBox {

    public function __construct() {

        require 'smallBox.php';
        $box = new SmallBox();
        $box->boxMethod();

    }

}
?>

I am new to PHP OOP and MVC and was wondering if including smallBox.php in the BigBox class is considered bad practice?

Upvotes: 2

Views: 133

Answers (3)

galymzhan
galymzhan

Reputation: 5523

Instead of manually require-ing PHP files, you should use autoloading of classes. Basically, it's a mechanism of loading appropriate PHP files based on a class name.

Upvotes: 4

Nikita Melnikov
Nikita Melnikov

Reputation: 209

Use required_once and include_once. Use include structure before class declaration

include_once 'path/to/class/a.php';

class B extends A
{
  public function __construct()
  {
     // your code
  }

}

Upvotes: 2

Phix
Phix

Reputation: 9890

That will work, but remember when you include or require other files, those files variables will operate within the scope of where it's included. I once tried to emulate javas import behavior with a "loader" class, but ran into this issue as the classes I was loading weren't available outside of that main class' scope. Check the manual for more clarity.

Upvotes: 1

Related Questions