سؤال

I've searched for similar questions but didn't find any. The usual problem is that a certain class cannot be redeclared in another class, and so the solution is to use "require_once" or "include_once". But my error is not allowing the class itself to redeclared!

Let me explain, I have two classes, Design and DesignSide. I have a bunch of PHP files where I use these two classes. - build_design.php, - browse_designs.php, which gives an AJAX call to - load_designs.php

Each design can have a few sides to it, so all 3 files above include the line:

require_once("Design.php");

and Design.php has the line:

require_once("DesignSide.php");

But on build_design.php, my error is:

Fatal error: Cannot redeclare class DesignSide in ../classes/DesignSide.php on line 4

i.e. it's objecting to DesignSide declaring itself! These are the beginning lines of DesignSide:

<?php

class DesignSide
{
private $id;
private $data;
private $designtag;
private $side;

What's wrong?

هل كانت مفيدة؟

المحلول

...or else you can use one of PHP's magic __autoload in your scripts to prevent this kind of behavior.

Save this file as config.php

function __autoload( $class ) {
    if( file_exists( $class . '.php' ) ) {
        require_once $class . '.php';
    } else {
        die( 'No such file.' );
    }
}

Now, include/require config.php in all your files and you don't need to include/require the class files.

Only caveat is that the class names must match the file name.

نصائح أخرى

Someone just deleted their answer - but I was just coming to tick it as the right answer. It turned out that in fact I did have "DesignSide.php" included twice, in build_design.php. Thanks! My bad!

So the correct answer was to include the DesignSide class in Design, and only include the Design class in the three php files.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top