0

To avoid getting the error message as in this previous question, I decided to change the class with __get() like this below,

class property 
{

    public function __get($name)
    {
        return isset($this->$name) ? $this->$name : new property;
    }
}



class objectify
{

    public function array_to_object($array = array(), $property_overloading = false)
    {
        # if $array is not an array, let's make it array with one value of former $array.
        if (!is_array($array)) $array = array($array);

        # Use property overloading to handle inaccessible properties, if overloading is set to be true.
        # Else use std object.
        if($property_overloading === true) $object = new property();
            else $object = new stdClass();

        foreach($array as $key => $value)
        {
            $key = (string) $key ;
            $object->$key = is_array($value) ? self::array_to_object($value, $property_overloading) : $value;
        }


        return $object;

    }
}

$object = new objectify();
$type = null;
$type = $object->array_to_object($type,true);
var_dump($type->a->b->c);

so I get this result in the end,

object(property)#3 (0) { }

but it is still not perfect. as my understanding, the above solution processes the object in a chain like this,

$type = object{}->object{}->object{}

so I wonder if I can find whether it is the last chain and it is empty then just output a null?

$type = object{}->object{}->NULL

is it possible with PHP?

EDIT:

I have thought of an idea which is to count how many times the property class has been instantiated,

class property 
{
    public static $counter = 0;

    function __construct() {
        self::$counter++;
    }

    public function __get($name)
    {
        if(isset($this->$name))
        {   
            return $this->$name;
        }
        elseif(property::$counter < 3)
        {
            return new property;
        }
        else
        {
            return null;
        }

    }
}

but my only problem is how to make the number 3 dynamic. Any ideas?

Community
  • 1
  • 1
Run
  • 54,938
  • 169
  • 450
  • 748

1 Answers1

0

Sounds like you're looking for a PHP version of Groovy's ?. operator: http://groovy.codehaus.org/Null+Object+Pattern

Afaik, you can't overload or create a new operator in PHP. You could perhaps simulate it by passing all of your nested calls to a function, and the function knows when to return null.

Edit: other options posted here - http://justafewlines.com/2009/10/groovys-operator-in-php-sort-of/

Cory Carson
  • 276
  • 1
  • 6