2

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?

3
  • You might get a better answer over at cstheory.stackexchange.com Commented Nov 28, 2012 at 5:07
  • bad\good its all situational. Commented Nov 28, 2012 at 5:20
  • try autoloading instead Commented Nov 28, 2012 at 9:15

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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 } } 

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.