Переписать класс Ruby в класс PHP

Я пытаюсь преобразовать некоторые классы из Ruby в PHP для проекта, над которым я работаю. Я думаю, что почти у меня это есть, но я не разбираюсь в Ruby, поэтому я пытаюсь понять некоторые аспекты и каковы будут эквиваленты в PHP.

Итак, класс Ruby выглядит следующим образом:

class Log
def initialize (x,y,list,url)
@line = 0
@x=x
@y=y
@url=url
@list=list
@points = Hash.new(0)
@list.each do |point|
@points[point.xy] +=1
end
@reps = @points.values.max
end
attr_reader :x, :y, :list, :reps, :url
def next
coord = @list[@line]
@line += 1
return coord
end
end

Вот что я написал на PHP до сих пор: (Я также добавил примечание о том, что должен делать оригинал)

<?php
/*
* Stores all the values pertinent to a single URL and gives accessors to them.
* There’s also a “next” method that returns next click within the same URL
*/
class Log
{
private $x;
private $y;
private $url;
private $list;
private $reps;
private $points;

function __construct($x,$y,$list,$url)
{
$this->line = 0;
$this->x = $x;
$this->y = $y;
$this->url = $url;
$this->list = $list;
$this->points = array();
foreach ($list as $l_attr => $l_val) {
if($l_attr == 'xy'){
$this->points[$l_val];
}
}
$this->reps = count($this->points);

return $this;
}

function next(){
$coord = next($this->list);

return $coord;
}

public function __get($property) {
if (property_exists($this, $property)) {
return $this->$property;
}
}
}

Я стараюсь, чтобы все ООП соответствовало остальной части моего проекта.

Я действительно хотел бы знать, правильно ли я делаю это или я далеко. 😉

1

Решение

Я плохо разбираюсь в ruby, поэтому мне сложно разобраться в коде, но это должно быть довольно точно:

<?php

class Log {
private $line = 0;
private $x;
private $y;
private $url;
private $list;
private $reps;

public function __construct($x, $y, $url, $list)
{
$this->x = $x;
$this->y = $y;
$this->url = $url;
$this->list = $list;
$points = [];

foreach ($list as $point) {
$points[$point['xy']] += 1;
}

$this->reps = max($points);
}

public function getX()
{
return $this->x;
}

public function getY()
{
return $this->y;
}

public function getUrl()
{
return $this->url;
}

public function getList()
{
return $this->list;
}

public function getReps()
{
return $this->reps;
}

public function next()
{
$coord = $this->list[$this->line];
$this->line += 1;

return $coord;
}
}

Я не уверен насчет $points[$point['xy']] += 1; часть, поскольку это не имеет смысла для меня, поэтому обязательно исправьте это, как считаете нужным. Также рекомендуется определять сеттеры вручную, а не использовать магические методы, такие как __get ().

0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector