php - Set an array from class and get him outside a class -


i create array id posts inside function, , him outside class. code:

<?php   class cat_widget extends wp_widget {  private $newhomepost = array(); 	  	  	function widget($args, $instance){	        //...          foreach($img_ids $img_id) {   		if (is_numeric($img_id)) {  			$this->setnewhomepost($newscounter,$post->id);  			$newscounter++;                            //...          }        }      }  	function setnewhomepost($num, $value){   		$newhomepost[$num] = $value;  	}  	function getnewhomepost(){           return "id: ".$this->newhomepost[0];      }  }    $testa = new cat_widget();  echo $testa->getnewhomepost();  ?>

i receive on screen resuld: id: (without id)

but if insert inside setnewhomepost() echo array, i'll obtain correctly array inside , not outside class.

    	function setnewhomepost($num, $value){       		$newhomepost[$num] = $valore;      		echo $newhomepost[0];      	}
seem array works fine inside "function widget", doesn't works outside it. can me, please?

function setnewhomepost($num, $value){      $newhomepost[$num] = $value; } 

this creates local variable named $newhomepost, setting value @ index , returning. once returns, local variable disappears. linked manual page:

any variable used inside function default limited local function scope.

you want set class member property newhomepost instead:

function setnewhomepost($num, $value) {      $this->newhomepost[$num] = $value; } 

update

this how have method defined:

function getnewhomepost() {     return "id: " . $this->newhomepost[0]; } 

i suspect you're still fiddling , trying work. if want ever return 0'th index, try instead:

function getnewhomepost() {     return isset($this->newhomepost[0]) ? $this->newhomepost[0] : null; } 

when building class remember cannot make assumptions order public methods can called object or calling code (even if calling code exists inside of class. methods public, meaning can call them). code above assumes nothing in not have call addnewhomepost prior getnewhomepost. imagine if in logs may see few notice: undefined index.. type errors.

also sure check on calling side:

$myclass = new cat_widget; $myclass->setnewhomepost(0, 'my new home post!');  $homepost = $myclass->getnewhomepost(); echo $homepost ? $homepost : 'none'; 

i think better getter method this:

function getnewhomepost($i) {     return isset($this->newhomepost[$i]) ? $this->newhomepost[$i] : null; } 

Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

python - build a suggestions list using fuzzywuzzy -