Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I have a method which only needs to be executed once in PHP but will be called twice. How do I structure this?

Tags:

php

I have a method in PHP which calls a SOAP service, parses some data and returns it.

It will return the same data - it asks how many records in a data object.

I need to call it twice with a pass.

My question is, what is best practice for structuring this in PHP? I've tried to see if the function has been called already.Do I use static variables / functions?

function MinimumRequired() { 
        return $this->NumberPeopleJoined();
    }   

function NumberPeopleJoined () {
        if (isset($NumberPeople)) {
            Debug::Show($NumberPeople);
        }
        static $NumberPeople;
        $NumberPeople = Surge_Controller::NumberPeopleJoined();
        return $NumberPeople;
    }

Thanks!

like image 441
Nick Avatar asked Nov 22 '25 12:11

Nick


1 Answers

Just create a local class member, and check if that has a value. If not, set the value to whatever is retrieved from Surge_Controller, and if it was already set, just return the value:

<?php

class Surge_Controller {
    static public function NumberPeopleJoined() {
        echo "Surge_Controller::NumberPeopleJoined() got called.\n";
        return 2;
    }
}

class Foo {
    protected $cacheNumberPeople;

    function MinimumRequired() { 
        return $this->NumberPeopleJoined();
    }   

    function NumberPeopleJoined () {
        if( !isset( $this->cacheNumberPeople ) ) {
            $this->cacheNumberPeople = Surge_Controller::NumberPeopleJoined();
        }
        return $this->cacheNumberPeople;
    }
}

$foo = new Foo( );
echo $foo->numberPeopleJoined( ) . "\n";
echo $foo->numberPeopleJoined( ) . "\n";

Output:

$ php foo.php
Surge_Controller::NumberPeopleJoined() got called.
2
2
like image 173
Berry Langerak Avatar answered Nov 24 '25 03:11

Berry Langerak