Question

In main.php, autoload is added and a new object is created:

function __autoload($class) {
    require_once($class . '.php');
}
...
$t = new Triangle($side1, $side2, $side3);

In Triangle.php:

class Triangle extends Shape {...}

Shape.php is an abstract class:

abstract class Shape {
    abstract protected function get_area();
    abstract protected function get_perimeter();
}

I can see that __autoload function calls Triangle.php, but does it call Shape.php at the same time?

Was it helpful?

Solution

No (not at the exact same time), but yes (it will get loaded and everything will work).

When you call new Triangle it will see that Triangle is a class which hasn't been loaded yet, so it calls __autoload(). This will then require_once the Triangle.php file.

In parsing Triangle.php it sees that there's another class which hasn't been loaded (Shape) so it repeats the process.

In short, there's nothing more you need to do than what you've got, but it does it in a number of passes.

OTHER TIPS

It should, yes. I guess you could verify that by simply adding an

echo "loaded $class!\n";

statement to your __autoload handler?

autoload is executed every time a class definiton can not be found.

In your case it will first be called for Triangle, then the parser encounters reference to Shape in Triangle.php and will then autoload Shape.php

<?php
function __autoload($class) {
    print "autoloading $class\n";
    require_once($class . '.php');
}

$t = new Triangle();

[~]> php test.php 
autoloading Triangle
autoloading Shape
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top