Jump to content

Questions about an arg in a method


eldan88

Recommended Posts

Hey Guys. I came across a method that had an argument without  a dollar sign next to it. (Talk)

 

I was just wondering how that works since I never seen it before. Below is an  example

 

Thanks your help in advance!

class Speaker {

protected $talk; 

public function setTalk(Talk $talk) { // No dollar sign on the first argument for.. Not sure
what it is used for?

}

$this->talk =  $talk;

public function getTalkTitle {

return $this->talk-getTitie(); 

}

}
Link to comment
https://forums.phpfreaks.com/topic/286388-questions-about-an-arg-in-a-method/
Share on other sites

Hey Guys. Thanks for your response. I did come across a tutorial on youtube about type hinting. I sort of understand it now. The one one thing I don't understand is why is there a need to use the construct function on the test class, what does it exactly construct?? Below is the code. Thanks for your help in advance. 

<?php 

class Test { 

public function __construct(){


}

public function Write() {
	echo "I am writing from Test";
}



} // end  of class test

class Foo {

public function __construct(Test $a) {

$this->Newobj = $a; 
$this->Newobj->Write();

}


}




 new foo(new Test);




?>

Every object has a constructor.  Test's explicitly empty constructor is a bit redundant since if you try instantiating a class that doesn't have a constructor, PHP's general purpose default constructor will execute instead.  A working example of that in action:

 

class Example
{
    public function blah()
    {
      echo "blah";
    }
}
    
$x = new Example();
$x->blah(); // echoes "blah"
Notice that new Example still worked even though I didn't write a constructor.

 

Foo's constructor is written so that it will only accept an object of type Test as an argument.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.