Search code examples
phpwordpressscopeprocedural-programming

Accessing variable from outside class definition?


I am new to PHP, and whatever little I know is the "functional programming" side of it. I am using a plugin that appears to follow the "object oriented programming" style, and would like to access a variable for use within my own function. I don't know how to do it.

To give you an idea, this is what the class definition in the plugin looks like (kind of):

<?php

    class WPSEO_Frontend {
        public function canonical() {
            $canonical = get_page_link();
        }
    }
?>

And this how another file in the plugin calls the variable $canonical:

<?php
    class WPSEO_Twitter extends WPSEO_Frontend {
        public function twitter_url() {
            echo '<meta name="twitter:url" content="' . esc_url( $this->canonical() ) . '"/>' . "\n";
        }
    }
?>

Now, I want to be able to access $canonical variable (in functional programming style) in my function, in a different file. For example, like this:

<?php
    function seo_meta_tags() {
        echo '<meta property="og:url" content="' . $canonical . '">' . PHP_EOL;
    }
?>

How do I do that? Is it possible?

PS: Given my knowledge I don't know if I am missing anything, so please do let me know.


Solution

  • There are a couple of issues here.

    1. Your WPSEO_Frontend::canonical function should return a value so that when other parts of your code calls the function a value instead of void is returned.
    2. Since canonical is a member function of WPSEO_Frontend you need to have an instance of WPSEO_Frontend to call the canonical function.

    Update WPSEO_Frontend::canonical function to return get_page_link():

    <?php
    
        class WPSEO_Frontend {
            public function canonical() {
                return get_page_link();
            }
        }
    ?>
    

    Then in your seo_meta_tags function use an instance of WPSEO_Frontend to call canonical:

    <?php
        function seo_meta_tags() {
            $wp_seo_frontend = new WPSEO_Frontend();
            echo '<meta property="og:url" content="' . $wp_seo_frontend->canonical() . '">' . PHP_EOL;
        }
    ?>