1

maybe this is easy for most. But sometimes in a piece of code i see something like this:

public function myFunction(Class_Name $var){
  //some nice code here
}

My question is, those paramaters what do they do and why do i want to use it? :)

5 Answers 5

9

The Class_Name portion is a type hint. The $var parameter must be an instance of that class (whether a new Class_Name() or an instance of any class that derives from it). You use it if you expect $var to be a certain kind of object, and not just any arbitrary PHP value. Type hints only exist natively for class/interface types and arrays, though.

Sign up to request clarification or add additional context in comments.

1 Comment

Type hints exist for arrays, too.
3

This means that the variable, passed to myFunction must be instance of Class_Name. In this way you can avoid checking the type of the variable in the body of myFunction, or calling a method of $var whitout being sure that that method exists.

Comments

2

A parameter is used for whatever you (or someone else) use it within the function/method.

public function myFunction(Class_Name $var){
  //some nice code here
  echo $var->someProperty;
}

If you are asking, whats Class_Name about: That's a type-hint. It means, that php will emit an error everytime you try to set anything else than an object of class Class_Name (or of an child class) as agument.

Comments

1

That's called typehinting and it assures that the $var variable is an instance of either Class_Name, or a class that extends Class_Name. It's just an assertion, really.

Comments

0

for a function arguments have to be defined if you want to return some result from the function .... class_name is like (int,float ...etc ) which is not necessarily be defined and $var can be any name you want your variable

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.