Skip to content

Instantly share code, notes, and snippets.

@hhamon
Created June 13, 2011 10:31
Show Gist options
  • Select an option

  • Save hhamon/1022581 to your computer and use it in GitHub Desktop.

Select an option

Save hhamon/1022581 to your computer and use it in GitHub Desktop.
<?php
#
# Even if the $bar property is private, it can be accessed publicly and modified by the modify() method
# that modifies an instance of the same PHP class.
#
class Foo
{
private $bar;
public function __construct($bar)
{
$this->bar = $bar;
}
public function modify(Foo $foo)
{
$foo->bar = 'C';
}
}
$a = new Foo('A');
$b = new Foo('C');
$b->modify($a);
# $a->bar now equals 'C'
var_dump($a);
@mathiasverraes

Copy link
Copy Markdown

That actually makes sense, so I wouldn't count it as a phpsadness. I agree it feels a bit counterintuitive, because the visibility is class-level instead of object-level. I wrote about it a few months back: http://blog.verraes.net/2011/03/accessing-private-properties-from-other-instances/

@hhamon

hhamon commented Aug 1, 2011

Copy link
Copy Markdown
Author

Thanks for your blog post.

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