Skip to content

Instantly share code, notes, and snippets.

@lastguest
Last active May 23, 2017 14:29
Show Gist options
  • Save lastguest/b0f270c4000330a37c6d9d6986d3f5db to your computer and use it in GitHub Desktop.
Save lastguest/b0f270c4000330a37c6d9d6986d3f5db to your computer and use it in GitHub Desktop.
[CAFFEINA] Exercise #1
<?php
include "tree.php";
$x = new Tree();
$x->bacon = "Pancetta";
$x->pasta["fagioli"] = 3;
$y = clone $x;
$y->pasta = null;
$y->pasta->fagioli = [1];
$y->alpha->beta->gamma = "Carote";
var_dump($x,$y);
echo "\n$x\n$y";
<?php
/**
* Develop the class responsibile for the provided output in file : video.output.txt
*/
class Tree {}
object(Tree)#1 (2) {
["bacon"]=>
string(8) "Pancetta"
["pasta"]=>
object(Tree)#2 (1) {
["fagioli"]=>
int(3)
}
}
object(Tree)#3 (3) {
["bacon"]=>
string(8) "Pancetta"
["pasta"]=>
object(Tree)#4 (1) {
["fagioli"]=>
array(1) {
[0]=>
int(1)
}
}
["alpha"]=>
object(Tree)#5 (1) {
["beta"]=>
object(Tree)#6 (1) {
["gamma"]=>
string(6) "Carote"
}
}
}
{"bacon":"Pancetta","pasta":{"fagioli":3}}
{"bacon":"Pancetta","pasta":{"fagioli":[1]},"alpha":{"beta":{"gamma":"Carote"}}}
@smokills
Copy link

smokills commented May 23, 2017

<?php

class Tree implements 
	\ArrayAccess,
	\JsonSerializable
{
	private $container = null;

	private $value = null;
	
	public function __construct($value = null) 
	{
		$this->container = [];

		$this->value = $value;
	}
	
	public function offsetSet($offset, $value) 
	{
		(empty($offset)) 
			? $this->container[] = $value
			: $this->container[$offset] = $value;
	}

	public function offsetExists($offset) 
	{
		return isset($this->container[$offset]);
	}

	public function offsetUnset($offset) 
	{
		unset($this->container[$offset]);
	}

	public function offsetGet($offset) 
	{
		return empty($this->container[$offset]) 
				? null 
				: $this->container[$offset];
	}

	public function __set($key, $value) 
	{
		$this->container[$key] = new self($value);
	}

	public function __get($key) 
	{
		return empty($this->container[$key])
				? $this->container[$key] = new self()
				: $this->container[$key];
	}
	
	public function __clone() 
	{
		$this->value = $this->value;

		$this->container = (array) (clone((object) $this->container));
	}

	public function __toString() 
	{
		return json_encode($this);
	}

	public function __debugInfo() 
	{
		return (array)$this->jsonSerialize();
	}

	public function jsonSerialize() 
	{
		return empty($this->container) 
				? $this->value  
				: $this->container;
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment