Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Using your example:</p> <pre><code>$foo = new Person; $foo-&gt;name = 'smith'; $something = doSomething($foo); echo $something; </code></pre> <p>Type hinting means that whatever you pass must be an instance of (the same type as) the type you're hinting.</p> <p>So, if you hint to <code>Person</code> only objects of that type will be accepted.</p> <p>In the example you gave, you tried to pass a string instead of an object.</p> <p><strong>Update</strong></p> <p>"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.</p> <p>So, let's say you have a function <code>sing()</code>. You want to be sure that it will only accept objects of type <code>Song</code>.</p> <p>Let's create our class <code>Song</code>:</p> <pre><code>class Song{ public $title; public $lyrics; } </code></pre> <p>and our function sing(). We will type hint to <code>Song</code> to ensure that no other type of params can be passed to it:</p> <pre><code>function sing(Song $song){ echo "Singing the song called " .$song-&gt;title; echo "&lt;p&gt;" . $song-&gt;lyrics . "&lt;/p&gt;"; } </code></pre> <p>Now, again, the function can ONLY accept objects of type <code>Song</code> because that's what we hinted to in the declaration (<code>Song $song</code>).</p> <p>Let's create a Song and pass it:</p> <pre><code>$hit = new Song; $hit-&gt;title = "Beat it!"; $hit-&gt;lyrics = "It doesn't matter who's wrong or right... just beat it!"; </code></pre> <p>then we call:</p> <pre><code>sing($hit); </code></pre> <p>Which will work just fine.</p> <p>Now, let's say we have a class <code>Poem</code>:</p> <pre><code>class Poem{ public $title; public $lyrics; } $poem = new Poem; $poem-&gt;title = "Look at the sea"; $poem-&gt;lyrics = "How blue, blue like the sky, in which we fly..." </code></pre> <p>If we try to call it using our function 'sing';</p> <pre><code>sing($poem) </code></pre> <p>we will get an error because <code>$poem</code> is not the type of object we've hinted to when creating the function <code>sing()</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload