开发者

How does PHP see classes - only in include files?

In PHP are classes only seen when they are in an include file? In Jav开发者_运维问答a I can see them in another file without including that file in my current file. In PHP is the only way to see any given class to include it in your file? So I'm just including my class file(s) everywhere?


In PHP are classes only seen when they are in an include file?

Yes. However, in PHP 5, there is the new Autoloading feature that allows you to build a function that includes a file when a class name is invoked. That effectively makes it possible to auto-initialize classes.

The simple example in the manual (I extended it slightly) makes it clear how this works:

<?php
function __autoload($class_name) {
    require_once $class_name . '.php';
}

$obj  = new MyClass1();   // Autoloader will load "MyClass1.php" 
$obj2 = new MyClass2();   // Autoloader will load "MyClass2.php" 
?>

Advanced autoloaders like Zend Framework's Zend_Loader_Autoloader (and the Standard PHP Library's spl_autoload_register(), cheers @ircmaxell) make it even possible to add different autoloading rules for different prefixes, allowing for libraries to be loaded from varying directories with varying naming conventions.


Generally speaking, yes. However, do note that includes are cascaded--in the sense that: if you include file a.php which includes file b.php, you can now see file b.php in your current file.

Also, PHP 5 offers Autoloading Classes which I recommend you take a look at:

http://php.net/manual/en/language.oop5.autoload.php


Yes -- PHP doesn't have any visibility into code which wasn't included directly in the file using the code.

However, instead of including (or the preferred method -- requiring) .php files everywhere, many developers choose to use the PHP autoload ability (http://php.net/manual/en/language.oop5.autoload.php) to automatically load the required file when you use a particular class.


Yes, for a class in a file to be available, that file has to be included.

Including a file can be done in a number of ways, either using the following functions:

include(filename);
include_once(filename) - which only includes the file if it's not already loaded
require(filename) - equal to include, except that the script will halt if file is not available
requier_once(filename)

Files can also be autoloaded through the __autoload or spl_autoload_register functions. More info on autoloading classes on PHP.net.


Yes only in include statements will you have access to the functions in other php files. PHP is by standard a Procedural language. It works from the top order down, so if you wish to perform class like includes look at Object Oriented PHP or include the files at the top of the php page.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜