Skip to content

Commit

Permalink
Allow setting properties after instantiation
Browse files Browse the repository at this point in the history
I find it more readable to assign properties/methods after instantiation,
like so:

```
$stub = new s();
$stub->foo = 'bar';
$stub->callMe = function() {};
```

This commit allows doing just that.
  • Loading branch information
sergeylukin committed Nov 5, 2014
1 parent 937e975 commit 5b4357f
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,13 @@ $stub = new Stub([
'answer' => 42,
'callMe' => function($a) { return $a; } # Anything which is a callable
]);
$stub->foo = 'bar';
$stub->myMethod = function() { return 50; };
echo $stub->answer(); # => 42
echo $stub->answer; # => 42
echo $stub->callMe('maybe'); # => 'maybe'
echo $stub->foo; # => 'bar'
echo $stub->myMethod(); # => 50
echo $stub->lol()->hey(); # => $stub

// Different configurations
Expand Down
5 changes: 5 additions & 0 deletions src/Nulpunkt/PhpStub/Stub.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ public function __get($name)
}
return null;
}

public function __set($name, $value)
{
$this->methods[$name] = $value;
}

public function __isset($property)
{
Expand Down
14 changes: 14 additions & 0 deletions test/Nulpunkt/PhpStub/StubTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,20 @@ public function testThatAStubRespondToDefinedMethods()
$this->assertSame(42, $stub->getId());
}

public function testThatMethodsCanBeAssignedAfterInstantiation()
{
$stub = new Stub();
$stub->myMethod = function() { return 42; };
$this->assertSame(42, $stub->myMethod());
}

public function testThatPropertiesCanBeAssignedAfterInstantiation()
{
$stub = new Stub();
$stub->foo = 'bar';
$this->assertSame('bar', $stub->foo);
}

public function testThatItHasAllProperties()
{
$stub = new Stub();
Expand Down

0 comments on commit 5b4357f

Please sign in to comment.