Home > database >  Using class methods in another file not working in WordPress
Using class methods in another file not working in WordPress

Time:07-11

I'm trying to include a class in PHP and to use the methods from this class in another file. My code looks like that (small reproducable example). By the way: I'm working on a WordPress environment.

Main file:

include 'class-file.php';

$cars = new Cars();
var_dump($cars->getCars());

File class-file.php:

class Cars {

  public function getCars() {
    return "No Cars";
  }

}

I get the following error:

Fatal error: Uncaught Error: Call to undefined method Cars::load() in /..../wp-content/themes/builder/includes/elements.php

Seems that my class instance is connected with another class from the theme. But why? Can I disconnect the class from any others? If yes, how?

CodePudding user response:

Maybe the theme doesn't use namespaces, which makes all its classes discoverable from the global namespace, and by defining your own Cars class, you override the theme's class.

Try to define your namespace, and check if the conflict is gone.

Main file:

include 'class-file.php';

$cars = new \mycode\Cars();
var_dump($cars->getCars());

File class-file.php:

namespace mycode;

class Cars {

  public function getCars() {
    return "No Cars";
  }

}
  • Related