Jenny
Jenny

Reputation: 1727

How to avoid repeatedly calling a function in this case?

I wrote a function to display an object on each wordpress post:

function pod(){
global $post,$pod;
$id = get_the_ID();
$pod = new WP_POD( $id );
return $pod;
}

I thought $pod is global, so, I can use $pod->stuffs when need, but it doesn't work. So, in each function I need to use stuffs in the object, I have to add one line:

$pod = pod()

I think repeatedly calling this function might not good for performence. Is there a way to make this global and accessable by other functions?

Upvotes: 1

Views: 182

Answers (4)

Gordon
Gordon

Reputation: 316959

You want to avoid the global keyword. If you need to pull in data to a function, its a sure sign that your design is broken (and Wordpress is broken). Use Dependency Injection and pass in $post and $pod to the function (that will also prevent spooky action at a distance):

function pod($post, $pod)
{
    $id = get_the_ID();
    $pod = new WP_POD( $id );
    return $pod;
}

However, that still doesnt make much sense. You are not using $post within the function, so why pass it in? Instead, you reach out of the function scope again to fetch some sort of id. And you use that to instantiate a WP_POD instance and assign it back to the global scope.

Why not just do

function createPod($id)
{
    return new WP_POD($id);
}

and then call it with

$pod = createPod(get_the_ID());

or just delete the function altogether and just do

$pod = new WP_POD(get_the_ID());

Yes, that wont assign the $pod instance to the global scope, but I doubt that you really need it there anyways.

As for performance: you should not worry about performance unless you have profiled your application and found that it's running slow and that particular code is indeed the reason for it being slow.

Upvotes: 1

castleofbones
castleofbones

Reputation: 53

You can use $GLOBALS to declare the variable in your script:

$pod = new WP_POD( get_the_ID() );

function myFunc() {
    $GLOBALS['pod']->aMethod;
}

Upvotes: 0

VolkerK
VolkerK

Reputation: 96159

You could simply pass the object to the functions you're calling.
Or use something else related to http://en.wikipedia.org/wiki/Dependency_injection

Or, if that doesn't convince you ;-), at least limit the visibilty of the variable via something like

function pod($init=false) {
    global $post,$pod;
    static $pod=null;
    if ( is_null($pod) || $init ) {
        $id = get_the_ID();
        $pod = new WP_POD( $id );
    }
    return $pod;
}

see http://docs.php.net/language.oop5.static

Upvotes: 1

Sqoo
Sqoo

Reputation: 5243

You need to delcare $pod as global in the function you are trying to access the variable from. Variables are not accessible globally unless explicitly declared in PHP unlike most other languages.

Call pod() once

then access like this

global $pod;
$pod->stuffs .... 

Upvotes: 0

Related Questions