Using your example:
$foo = new Person;
$foo->name = 'smith';
$something = doSomething($foo);
echo $something;
Type hinting means that whatever you pass must be an instance of (the same type as) the type you're hinting.
So, if you hint to Person
only objects of that type will be accepted.
In the example you gave, you tried to pass a string instead of an object.
Update
"Type hinting" forces you to only pass objects of a particular type. This prevents you from passing incompatible values, and creates a standard if you're working with a team etc.
So, let's say you have a function sing()
. You want to be sure that it will only accept objects of type Song
.
Let's create our class Song
:
class Song{
public $title;
public $lyrics;
}
and our function sing(). We will type hint to Song
to ensure that no other type of params can be passed to it:
function sing(Song $song){
echo "Singing the song called " .$song->title;
echo "<p>" . $song->lyrics . "</p>";
}
Now, again, the function can ONLY accept objects of type Song
because that's what we hinted to in the declaration (Song $song
).
Let's create a Song and pass it:
$hit = new Song;
$hit->title = "Beat it!";
$hit->lyrics = "It doesn't matter who's wrong or right... just beat it!";
then we call:
sing($hit);
Which will work just fine.
Now, let's say we have a class Poem
:
class Poem{
public $title;
public $lyrics;
}
$poem = new Poem;
$poem->title = "Look at the sea";
$poem->lyrics = "How blue, blue like the sky, in which we fly..."
If we try to call it using our function 'sing';
sing($poem)
we will get an error because $poem
is not the type of object we've hinted to when creating the function sing()
.