PHP: $myObject = new ClassName(); vs newClassName;
So, I 开发者_运维问答understand that sometimes people use parens and sometimes they don't when declaring an instance of a class as an object.
If I declare a class without arguments and then extend it to have arguments, will the initial class need to have had parens?
Furthermore, can I have a class with brackets and no specific parameter or reference variable declaration like this:
$myObject = clone ClassName();
And then use parameters for the class....
class User($param, $param2)
Or do classes ever even use parameters? I'm not really sure because there isn't an example of a class that takes parameters in my book....
First, I assume you mean new
instead of clone
. PHP does not require that you use parenthesis when creating a class.
class Foo { }
$foo = new Foo;
$foo = new Foo();
Both are valid.
Any arguments you send are passed to the __construct
function. That function (if it exists) is automatically called when you create the object.
class Foo
{
public function __construct($n)
{
echo "Hello, $n\n";
}
}
$foo = new Foo("World!");
That will output:
Hello, World!
If the constructor takes arguments, then it is an error (warning) if you don't send any.
Note that __construct
doesn't need to have parameters. It is valid to have a constructor that simply does something without any parameters.
Those parameters, eg
$myObject = new ClassAwesome($param1, $param2);
dont correspond to the class declaration, they relate to the constructor. An example:
//this is how you declare a class, there will not be a parenthesis here
class ClassAwesome {
//here is where the parameters are used when you instantiate a class
public function __construct($param1, $param2) {
//init code goes here
}
}
So basically the reason you dont see a class declaration with parameters is because they dont exist, the class constructor is where the parameters go.
精彩评论