1

In this example, I have an abstract class and two regular classes. The abstract class is not supposed to be used alone, so its constructor is protected. Some functions are defined within the abstract class.

One of those functions is a "clone" function, which is supposed to return a new instance of the current object. This function makes a copy of the current object.

Here's my question:
When trying to set $copy->baz ([2] in clone()), it works, because I'm in the class that defined this private property. However, this doesn't make sense to me (at least in this example), because $copy is another object (of the same class) - is it possible to force PHP to use the magic setter ("Setting private property") when setting a private property of another object (not class)?

abstract class ac
{
    private $baz = "fakedefault";

    function __set($name, $value)
    {
        die("Setting private property!");
    }

    function clone()
    {
        $copy = clone $this; //make copy
        //Test:
        $this->baz = "newval"; //[1] Works as expected
        $copy->baz = "newval"; //[2] Does not die!
        return $copy; //return copy
    }
}

class c1 extends ac
{
    function foo()
    {
        print $this->baz;
    }
}

class c2 extends ac
{
    function foo()
    {
        print $this->baz;
    }
}

function dostuff()
{
    $o = new c1();
    $o->baz = "thiswontwork"; //Private -> doesn't work
}
1
  • please review my latest edit on my answer - I think it might help. thx Commented Dec 12, 2011 at 23:26

2 Answers 2

1

You need to name your method __clone, not clone.

[edited to replace code]

try this:

<?

header( 'content-type: text/plain' );
abstract class ac
{
    private $name = 'default-value';

    public function __set($name, $value)
    {
        throw new Exception( 'Undefined or private property.' . $name );
    }

    function __clone()
    {
        // this does work - $this->name is private but is accessible in this class
        $this->name = 'Isaac Newton';
    }
}

class c1 extends ac
{

    function __clone()
    {
        // this does not work - $this->name is private to ac and can't be modified here
        $this->name = 'Isaac Newton';
    }

    function echoName()
    {
        echo $this->name;
    }
}

function dostuff()
{
    $o = new c1();
    //$o->otherVariable = 'test'; // won't work - it's undefined
    $a = clone $o;
}

dostuff();
Sign up to request clarification or add additional context in comments.

Comments

0
$this->__set("baz", "newval");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.