-2

Possible Duplicate:
Does the order of class definition matter in PHP?

class a {
    function __construct () {
        $obj = new b();
        echo $obj->sum();
    }
}

 class b  {

    function sum () {
        return 3+4;
    }

 }


$obj_a = new a();

this code works, but I interest how much justified is this code? that is: first time is writed class a, in him we call class b, but class b is writed after a. in this example, wille be better way writed class b before a? or not sense?

Community
  • 1
  • 1
Oto Shavadze
  • 40,603
  • 55
  • 152
  • 236

5 Answers5

4

No, the order in which the two classes are defined in the source file doesn't matter. As long as both are defined in the same file you move them around at will.

If the classes are not defined in the same file then things can get a little more complicated, but not in a way that will impact this kind of code.

Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806
  • If both are not in the same file use autoloading and nothing will be more or less complicated then before ;) – KingCrunch Oct 08 '12 at 11:55
  • @KingCrunch: Actually there are things that *can* be more complicated than before. I invite you to read the linked answer. :) – Jon Oct 08 '12 at 11:58
  • OK, I see, what you mean, but the conclusion from the linked answer is not completely right, because both instanciation and `get_class()` triggers the autoloader (that's what I meant). Thus I see the difference only in some internas, but nothing "important". – KingCrunch Oct 08 '12 at 13:18
  • @KingCrunch: `get_class()` has an optional parameter that can disable autoloading. So sure, highly specialized scenarios but it could happen. – Jon Oct 08 '12 at 15:04
2

That specific code contains elements of what we call "magic". There's no way you can infer from the code itself that it requires the b class to be defined.

The general rule to follow is, you should never read ahead to understand what you code does.

So in that sense, yes. Class b should (should, PHP don't care, it's for readability purposes only) be defined first, then Class a, then the object call.

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
1

You don't have to reverse the order. PHP compiles the code before running it.

ajon
  • 7,868
  • 11
  • 48
  • 86
0

The order in which classes are placed in a file does not matter. For classes placed in different files, check out this answer.

Community
  • 1
  • 1
aniri
  • 1,831
  • 1
  • 18
  • 28
0

When we run a file , it is searching for first execution line and this line is

$obj_a = new a();

it is not depend upon class or function initialization. So in any order your code will work.

Yogesh Suthar
  • 30,424
  • 18
  • 72
  • 100