Search code examples
phpwordpressstatic-variables

How to create a static variable and call it from another class?


I have a class called DB_Bookings, within that class I have a function called updated_variables() within this is a simple script to look at the date of a published post and change the name of a variable accordingly.

Doing this, throughout my app I intend to use the variable and it will change dynamically per post depending on the date created.

I am struggling to call the variables from within another class. Please see my working below:

class DB_Bookings {

...

public function updated_variables() {
    global $post;
    $compare_date = strtotime( "2018-05-22" );
    $post_date = strtotime( $post->post_date );

    if($compare_date > $post_date) {
        $weddingNameVariable = 'db-bookingsweddingname';

        ...
    } else {
        $weddingNameVariable = 'weddingName';
    }
}

} // end DB_Bookings class

Then in my other class (in a file called class-db-bookings-admin.php)

class DB_Bookings_Admin {

...

public function save_metabox( $post_id, $post ) {

...

    update_post_meta( $post_id, DB_Bookings::updated_variables($weddingNameVariable), $db_bookingsnew_weddingname );

...

}

} // end Class DB_Bookings_Admin

The idea here is that I can echo out the variable set in my DB_Bookings class and it can change based on the post date (this is essentially compensating for legacy variables as I overhaul the coding of the app).

However, it doesn't appear to be saving and I'm getting the following error

[22-May-2018 19:29:43 UTC] PHP Notice:  Undefined variable: weddingNameVariable in /var/www/html/wp-content/plugins/db-bookings/admin/class-db-bookings-admin.php on line 853

Solution

  • Another approach based on comments.

    class WeddingVariables {
    
        //add all of the variables needed to this class
        //you could create getters/setters to manage this data
    
        $variableA = "data";
    
        //get the variable
        public function get_variable_a() {
            return $this->variableA;
        }
    
        //set the variable
        public function set_variable_a( $value ) {
            $this->variableA = $value;
        }
    }
    
    //a global variable
    $WeddingVariables = new WeddingVariables();
    
    //admin class
    class DB_Bookings_Admin {
        public function save_metabox( $post_id, $post ) {
            global $WeddingVariables; //now we can access this within this method
    
            //get the value of a variable from the class
            $someVariable = $WeddingVariables->get_some_variable();
    
        }
    }