File Import Error in PHP

// FILE1.php
class file1 {

  function hi() {
     echo "hi from file1";
  }
}
// FILE2.php
# In this file I am going to use file1 functions

include_once './file1.php';
class file2 {

  function hibye() {

     $file1 = new file1; # Importing class from file1 
     $file1->hi();
     echo "bye from file2";
  }
}
// index.php
// In this file I want to use both file1 and file2 functions

include './file1.php';
include './file2.php';

$f1 = new file1;
$f2 = new file2;

$f1->hi();
$f1->hibye();

When I run index.php file it shows error saying file1 is already imported, Yes, I know that but, I want to explicitly include file1 again in index.php file.

How can I do this?

What if you change include_once to include in FILE2.php?

In fact, since class files are required to be included once and only once, use require_once every place you are currently using include. http://php.net/manual/en/function.require-once.php

And once you get a bit more comfortable with php, take a look at class autoloading. Pretty much eliminates the need for include statements.

1 Like

The real problem is you don’t seem to understand the fundamentals of OOP.

Master the understanding of abstraction, encapsulation, inheritance, and polymorphism.

1 Like

I think the problem might be understanding basic PHP. We don’t know the OP’s PHP skill level, but the use of include_once tells me they don’t have an understanding of why not to use it. If the OP is a beginner, then I strongly wouldn’t jump into doing OOP just yet. Learn the basics first. OOP is far more complicated than basic PHP syntax.

1 Like

Why?

1 Like

Maybe looking at what index.php looks like after the content of the includes is included will let you see the problem?

//include './file1.php';
class file1 {

  function hi() {
     echo "hi from file1";
  }
}

//include './file2.php';
//include_once './file1.php';
class file1 {

  function hi() {
     echo "hi from file1";
  }
}

class file2 {

  function hibye() {

     $file1 = new file1; # Importing class from file1 
     $file1->hi();
     echo "bye from file2";
  }
}

$f1 = new file1;
$f2 = new file2;

$f1->hi();
$f1->hibye(); 
2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.