问题
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?
回答1:
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.
回答2:
It should, yes. I guess you could verify that by simply adding an
echo "loaded $class!\n";
statement to your __autoload handler?
回答3:
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
来源:https://stackoverflow.com/questions/1420174/is-autoload-called-for-parent-classes-of-autoloaded-classes