myClass(123);
?>
this works, but returns this warning:
Warning: Missing argument 1 for myClass::myClass()
I read in to this, and seems that the constructor is expecting a value, so by adding:
function myClass($input='')
the warning is removed, but this seems so unnecessary?
could someone enlighten me as to why it’s required to define a value to prevent that warning?
thanks for any pointers
You are using a method (functions in objects are called methods) that is the same name as the class. That is called the constructor, it has a special meaning in OOP.
The constructor is never called separately, but is the method that gets called automatically when you initialize the object. Any parameters that method has, you append to the
new classnamestatement.also, the constructor must never return a value. It is used only to do things while initializing the class, e.g. storing parameters. Any returned values will be lost, as the result of
new myClassis always the initialized object.If you are just looking to create a method inside your class to return some text, then you need to change the method’s name. This would work:
If a constructor is indeed what you want to use, then note that since PHP 5, it is standard practice to use
__construct()instead of creating a method with the same name as the class:More on constructors and destructors in PHP 5 in the manual.