Question

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.

Was it helpful?

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;
    }
?>

OTHER TIPS

You would need to have an instance of the WPSEO_Frontend class (or the class that extends it). I'll call it $instance. You would then pass that variable into your function.

I'm assuming that first function either returns the value, or set it to a property using the $this keyword.

The WPSEO_Frontend class may have a getter function for that property, so you may need to do

$instance->getCanonical();

Or just

$instance->canonical;

Without seeing more of the actual code we can't tell you much more than that. If the function canonical() actually returns something, that is the function to call.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top