在 php 中调用类方法(带构造函数)而不进行对象实例化
我已经看过并尝试过,但找不到答案。
在PHP中,是否可以调用类的成员函数(当该类需要构造函数来接收参数时)而不将其实例化为对象?
代码示例(给出错误):
<?php
class Test {
private $end="";
function __construct($value) {
$this->end=$value;
}
public function alert($value) {
echo $value." ".$this->end;
}
}
//this works:
$example=new Test("world");
$example->alert("hello");
//this does not work:
echo Test("world")::alert("hello");
?>
Ive looked and tried but I can't find an answer.
In PHP, is it possible to call a class' member function (when that class requires a constructor to receive parameters) without instantiating it as an object?
A code example (which gives errors):
<?php
class Test {
private $end="";
function __construct($value) {
$this->end=$value;
}
public function alert($value) {
echo $value." ".$this->end;
}
}
//this works:
$example=new Test("world");
$example->alert("hello");
//this does not work:
echo Test("world")::alert("hello");
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
不幸的是 PHP 不支持这样做,但你是一个有创意和外观的家伙 :D
你可以使用“工厂”,示例:
Unfortunately PHP doesn't have support to do this, but you are a creative and look guy :D
You can use an "factory", sample:
只需这样做(在 PHP >= 5.4 中):
Just do this (in PHP >= 5.4):
我也在寻找一个单行代码来完成此任务,作为将日期从一种格式转换为另一种格式的单个表达式的一部分。我喜欢用一行代码来完成此操作,因为它是单个逻辑操作。因此,这有点神秘,但它允许您在一行中实例化和使用日期对象:
将日期字符串从一种格式单行转换为另一种格式的另一种方法是使用辅助函数来管理 OO 部分代码简介:
我认为面向对象的方法很酷而且很有必要,但它有时可能很乏味,需要太多的步骤来完成简单的操作。
I, too, was looking for a one-liner to accomplish this as part of a single expression for converting dates from one format to another. I like doing this in a single line of code because it is a single logical operation. So, this is a little cryptic, but it lets you instantiate and use a date object within a single line:
Another way to one-line the conversion of date strings from one format to another is to use a helper function to manage the OO parts of the code:
I think the object oriented approach is cool and necessary, but it can sometimes be tedious, requiring too many steps to accomplish simple operations.
如果没有实例,则无法调用实例级方法。你的语法:
没有多大意义。要么您正在创建内联实例并立即丢弃它,要么
alert()
方法没有隐式this
实例。假设:
你可以这样做:
但 PHP 语法不允许:
否则这将是等效的。 PHP 中有一些这样的例子(例如,在函数返回上使用数组索引)。事情就是这样。
You can't call an instance-level method without an instance. Your syntax:
doesn't make a lot of sense. Either you're creating an inline instance and discarding it immediately or the
alert()
method has no implicitthis
instance.Assuming:
you can do:
but PHP syntax doesn't allow:
which would otherwise be the equivalent. There are a few examples of this in PHP (eg using array indexing on a function return). That's just the way it is.
为此,您可以执行
https://www.php.net/manual/ en/reflectionclass.newinstancewithoutconstructor.php
反映您的类并触发不带构造函数的新实例。
这里是一个示例代码:
For this you can do a
https://www.php.net/manual/en/reflectionclass.newinstancewithoutconstructor.php
reflect your class and trigger the new instance without constructor.
Here a sample code: