Home > Back-end >  Initializing class properties
Initializing class properties

Time:07-08

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?

CodePudding user response:

$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.

  • Related