开发者

Scope of class declaration

开发者 https://www.devze.com 2023-01-09 22:19 出处:网络
I have a file classes.php in which I declare a set of classes to be used in a series of pages. Then, in one page, I need to use another class, that is declared in a separate file. Now, this separate c

I have a file classes.php in which I declare a set of classes to be used in a series of pages. Then, in one page, I need to use another class, that is declared in a separate file. Now, this separate class uses some classes located in the classes.php file.

So, in most pages, I have:

[1]
<?php
require('classes.php');
[page code]
?>

which works fine. The problem comes with that specific page, which has:

[2]
<?php
require('classes.php');
require('separate_class.php');
[page code]
?>

and this does not work because separate_class.php also requires classes.php.

If I try this:

[3]
<?php
require('separate_class.php');
[page code]
?>

then it does not work because now the classes are not available for this page, even if they are declared inside the separate_class.php file.

The obvious solution seems to be the inclusion of the separate class in the classes.php file, which is clumsy because this separate class makes sense only in this series of pages, while the file classes.php cont开发者_如何学Cains general purpose classes and is shared among various applications.

How can I do it in a way that allows me to keep a structure like shown in [2], that is, separating general-purpose classes from a specific class which, in turn, requires those general-purpose classes, while still being able to use these general-purpose classes in the page?


A more sound solution may be to seperate each class into it's own file and use an autoloader...

http://php.net/manual/en/function.spl-autoload.php


You want to use require_once()

EDIT: You can't redeclare a class if that's what you are trying to do. I don't know what your code looks like, but maybe inheritance is what you are looking for??

EDIT 2: I have only been able to reproduce your error when I had a require 'classes.php' in separate_class.php AND a require 'classes.php' in the script you are actually opening. So you have 2 options:

  • Don't require (or require_once) classes.php in your script before you have required separate_class.php
  • Use require_once everywhere (check separate_class.php) and don't worry about whether or not a file has been required.
0

精彩评论

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