php 实例化对象疑惑?

WBOY
Release: 2016-06-06 20:36:04
Original
982 people have browsed it

<code>Example #3 导入和动态名称

<?php use My\Full\Classname as Another, My\Full\NSname;

$obj = new Another; // 实例化一个 My\Full\Classname 对象
$a = 'Another';
$obj = new $a;      // 实际化一个 Another 对象
?>


http://php.net/manual/zh/language.namespaces.importing.php
上述代码在php手册看到的
为什么new 操作符在创建对象的时候没有加()小括号?
</code>
Copy after login
Copy after login

回复内容:

<code>Example #3 导入和动态名称

<?php use My\Full\Classname as Another, My\Full\NSname;

$obj = new Another; // 实例化一个 My\Full\Classname 对象
$a = 'Another';
$obj = new $a;      // 实际化一个 Another 对象
?>


http://php.net/manual/zh/language.namespaces.importing.php
上述代码在php手册看到的
为什么new 操作符在创建对象的时候没有加()小括号?
</code>
Copy after login
Copy after login

如果构造函数没有参数,加()或者不加()都可以。你可以试试。

括号主要是为了传入参数。
如果构造函数有参数就必须要括号,如果没有参数,加不加括号效果都相同。

这不是很好吗,当你需要根据不同上下文环境就可以不同的对象

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!