PHP构造函数和静态函数 [英] PHP constructors and static functions
问题描述
我对PHP中的构造函数有些困惑。
I'm a bit confused on how constructors work in PHP.
我有一个类,当我实例化一个新对象时,它会被调用。 p>
I have a class with a constructor which gets called when I instantiate a new object.
$foo = new Foo($args);
__ construct($ params)
Foo
并执行相应的初始化代码。
__construct($params)
is called in the class Foo
and it executes the appropriate initialization code.
但是当我使用类来调用静态函数,再次调用构造函数。
However when I use the class to call a static function, the constructor is called again.
$bar = Foo::some_function(); //runs the constructor from Foo
这将使构造函数执行,运行对象初始化代码,只有当我创建一个新的 Foo
对象。
This causes the constructor to execute, running the object initialization code that I intended only for when I create a new Foo
object.
我缺少构造函数的工作原理吗?或者有一种方法可以防止 __ construct()
在我使用类进行静态函数调用时执行?
Am I missing the point of how constructors work? Or is there a way to prevent __construct()
from executing when I use the class to make static function calls?
我应该使用工厂函数来做对象初始化吗?如果是,那么构造函数的要点是什么?
Should I use a "factory" function instead to do the object initialization? If so, what's the point of the constructor then?
:: EDIT ::
我有一个表单,用户可以将照片上传到相册(create_photo。 php)和他们可以查看相册的区域(view_photos.php)。提交表单后:
::: I have a form where users can upload photos to an album (create_photo.php) and an area where they can view the album (view_photos.php). Upon form submit:
$photo = new Photo($_FILES['photo'], $_POST['arg1'], ect..);
Photo构造函数创建并保存照片。但是在view_photo.php中,当我调用:
The Photo constructor creates and saves the photo. However in view_photo.php, when I call:
$photo = Photo::find_by_id($_POST['id']) //user-defined function to query database
这是Photo的构造函数的运行方式!
This is causing Photo's constructor to run!
推荐答案
我看不到有什么复制你的问题。
I see nothing that replicates your question.
查看演示: http://codepad.org/h2TMPYUV
代码:
class Foo {
function __construct(){
echo 'hi!';
}
static function bar(){
return 'there';
}
}
echo Foo::bar(); //output: "there"
这篇关于PHP构造函数和静态函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!