autoload
You said earlier that classes create one class per file?
Suppose the class for Disney is in disney.php and the class for marvel is in the marvel.php file.
If you have
a file show.php that uses both Disney and Marvel's classes, the
show.php file contains We'll include the .php file and create an instance.
As follows
include "disney.php"; include "marvel.php"; $disney = new disney; $marvel = new marvel;
This is just a simple example and a really large program will contain several classes.
As the program gets more complicated, I didn't include it by human error, but I might create an instance.
It's also annoying to include the file and create an instance every time.
Autoload makes this easier.
This is difficult to execute in the instance of Everlabel's coding editor, so run it in EEOS.
How to use autoload
function __autoload(parameter name to hold the class name) { include The parameter name to hold the class name.'.php'; }
__autoload function is a function that is called automatically when you create an instance.
The class name is used as a parameter.
In the above method, if the parameter name that contains the class name is $className, it will be as follows.
function __autoload($className) { include $className.'.php'; }
In other words, because it is designed like that, the file name that declares the class must be fixed.
If you match the file name with the class name, you can use
Rather I will use class-class.php
Then you should change it to
function __autoload($className) { include $className.'-class.php'; }
So let's look at an example.
It's convenient to do this in eeos, but we've taken steps to run this example in the coreasur coding editor, so you can see the results right away.
I made marvel.php and dinsey.php files in advance. Here is the contents of the disney.php file:
<?php class disney { function hello() { return 'disney'; } } ?>
I'll make a marvel.php file.
<?php class marvel { function hello() { return 'marvel'; } } ?>
This is an example of creating an instance of the disney and marvel classes. The most important example.
<?php function __autoload($className) { include $className.'.php'; } $mickey = new disney; echo $mickey->hello(); echo '<br>'; $ironMan = new marvel; echo $ironMan->hello(); ?>
The result of this code
Since we created an instance, the class name became an argument and the __autoload function was automatically executed to execute the command. ^^
<?php function __autoload($className) { echo "include {$className}.php"; include $className.'.php'; } $mickey = new disney; echo $mickey->hello(); echo '<br>'; $ironMan = new marvel; echo $ironMan->hello(); ?>
Result
So we learned about autoload. ^^