Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Initializing class properties

I need to initialize some properties in my class. I don’t use constructor, only set methods.

<?php

namespace Task;

class Log {
  private $_views = null;
  private $_urls = null;
  private $_traffic = null;

  /**
   * @param int $count
   */
  public function setViewCount(int $count) {
    $this->$_views = $count;
  }

  /**
   * @return int
   */
  public function getViewCount() {
    return $this->$_views;
  }

  /**
   * @param int $count
   */
  public function setUrlCount(int $count) {
    $this->$_urls = $count;
  }

  /**
   * @return int
   */
  public function getUrlCount() {
    return $this->$_urls;
  }

  /**
   * @param int $trafficData
   */
  public function setTraffic(int $trafficData) {
    $this->$_traffic = $trafficData;
  }

  /**
   * @return int
   */
  public function getTraffic() {
    return $this->$_traffic;
  }
}

?>

Then I try to set values to properties and save it to associative array.

<?php

require 'Log.php';

use Task;

$log = new Task\Log();
$log->setViewCount(44);
$log->setUrlCount(55);
$log->setTraffic(99999);

$res = array("views" => $log->getViewCount(), "urls" => $log->getUrlCount(), "traffic" => $log->getTraffic());
echo json_encode($res);
?>

After encoding to json I see that any element of array has last value I set to object. In this example last is 99999 for Traffic so I got {"views":99999,"urls":99999,"traffic":99999}. What’s the reason of such behaviour and how can I get correct values in each element of array?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

$this->$_views this accesses not the field named _views but a field with the name stored in variable $_views.

Since you have no such variable the name assumed empty, thus the same name for each of setters or getters.

In short: you need to remove $ after ->:

  $this->_urls = $count;

etc.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading