WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Class function calling another class as global (wrong scope?) (2 posts)

  1. e
    Member
    Posted 3 years ago #

    Hi guys,

    I am trying to call a class function from another class function but when calling global $hcdb; it loads as NULL. I read some time ago about having to declare it as a global but think it was only for variables. Any ideas? Sounds like quite a basic thing...

    Stripped code of the files below:

    main.php (the one that loads first)

    require_once(HC_PATH_INTERNAL."/includes/database.php");
    require_once(HC_PATH_INTERNAL."/includes/functions.php");
    
    $hc->format();

    database.php

    class HcDatabase {
      function checknicename() { return 1; }
    }
    $hcdb = new HcDatabase;

    functions.php

    class HcFunctions {
      function format() {
        global $hcdb;
        var_dump($hcdb); // returns NULL
        $hcdb->checknicename();
      }
    }
    $hc = new HcFunctions;
  2. e
    Member
    Posted 3 years ago #

    The code belonged to a former developer, and wasn't intended for WP. Just rewritten everything again to have a logical OOP structure that creates particular objects inside methods when needed, etc. Also adapted it to use functions so they are accessible through WP without hacks and everything keeps simplified, logical, scalable and secure

Topic Closed

This topic has been closed to new replies.

About this Topic