A
A
astrotrain2016-02-13 14:40:12
PHP
astrotrain, 2016-02-13 14:40:12

Associative array as object property in PHP?

Here is a sample code:

class GetInfo {    
        
        private $domains_ip = array();
        
        ...
        
        function get_ip($domain)
        {
            ...
    		
    		$ip = gethostbyname($domain);		
    		$this->domains_ip[$ip] = $domain;		
    		return $ip;      
            
        }
        
    }

But if you display $this->domains_ipit, it is empty all the time, that is, a new value is not added. Why is this happening and how to fix it. Thank you!
<?php 

class GetInfo {    
    
    private $domains_ip = array();
      
    function get_ip($domain)
    {
        
    print_r($this->domains_ip);
    $ip = gethostbyname($domain);		
    $this->domains_ip[$ip] = $domain;		
    return $ip;      
        
    }
    
}

//echo $o->get_ip("google.com");
//echo $o->get_ip("pivo.com");
//echo $o->get_ip("kone.ru");

class my_thread extends Thread {
  
  private $get_info_object;
  
  function __construct(GetInfo $obj)
  {
    $this->get_info_object = $obj;
  }
  
  function check_ip($domain)
  {
    echo $this->get_info_object->get_ip($domain);
  }
        
}
$o = new GetInfo();

$t = new my_thread($o);
$t->check_ip("google.com");
$t->check_ip("pivo.com");

In general, here is an example that shows that, for some reason, it does not work as expected.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Nemiro, 2016-02-13
@astrotrain

Everything seems to be working:
What is the state of $domains_ip at the time of adding the data?

function get_ip($domain)
{
  $ip = gethostbyname($domain);

  var_dump($this->domains_ip);

  if (!is_array($this->domains_ip))
  {
    echo 'domains_ip не является массивом!';
  }

  $this->domains_ip[$ip] = $domain;
  return $ip;   
}

What happens after adding?
function get_ip($domain)
{
  $ip = gethostbyname($domain);		
  $this->domains_ip[$ip] = $domain;

  var_dump($ip);
  var_dump($this->domains_ip);

  return $ip;      
}

What happens if an array is declared like this:
private $domains_ip = [];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question