我想弄清楚的是,实例化一个类是一种糟糕的做法
new Classname();
由于我需要运行类__construct,但我不需要使用该类。因为类中的其他函数将从__construct调用。
我想弄清楚的是,实例化一个类是一种糟糕的做法
new Classname();
由于我需要运行类__construct,但我不需要使用该类。因为类中的其他函数将从__construct调用。
它会起作用,但是,作为维护代码的人,我会对此感到非常困惑。一般来说,仅仅实例化一个对象没有副作用,所以我假设我可以删除那一行,一切都会正常工作。
我建议重新考虑你的代码结构,因为把有副作用的代码放在__construct
中肯定不是标准的。
请考虑使用以下内容:
class Foo
{
public static function do_something()
{
// ...
}
}
Foo::do_something();
虽然你所得到的会起作用,但还不清楚是否会发生什么。
(如果你坚持这样使用对象,至少在每次使用时都要清楚地记录下来。)
假设我们在一个文件中有一个名为HelloWorld的类名。
文件<code>class.HelloWorld.php</code>
class HelloWorld {
function __construct()
{
}
public function doSomething(){
echo "new HelloWorld()->doSomething() was called";
}
public function anotherMethod(){
echo "new HelloWorld()->anotherMethod() was called";
}
}
现在,您可以在运行时实例化类,而无需将其保存到变量中。
require( class.HelloWorld.php );
// you can just instantiate it and the constructur will be called automatically
(new HelloWorld());
// or you can instantiate it and call other methods
(new HelloWorld())->doSomething();
我不确定垃圾收集器是否会删除实例化的类,但我认为由于这些类没有保存到变量中,所以不会保存在内存中的某个地方,这将是完美的。
I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...
<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...
I found this script online that creates a thumbnail out of a image but the thumbnail image is created with poor quality how can I improve the quality of the image. And is there a better way to create ...
如何确认来自正确来源的数字。
Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...
I wonder there is a way to post a message to a facebook business page with cURL? thanks
I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...
How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...