简体   繁体   English

在php中重复创建对象

[英]Repeated object creation in php

i have my own php structure 我有我自己的php结构

that have controller and model now i want to export record from db to CSV file my question is that is php can manage garbage collection or memory resources? 有控制器和模型,现在我想将记录从db导出到CSV文件,我的问题是php可以管理垃圾收集或内存资源吗? because every time ajax request to a controller and controller make a object of model 因为每次对控制器的ajax请求和控制器都会使模型成为对象

every request is add limited row (as i define) eg 1000 rows to CSV and then again a ajax request is called for the same 每个请求都添加有限行(如我所定义),例如将1000行添加到CSV,然后再次针对相同请求调用ajax请求

i have large data so i just want to know is every time creating object of controller and model are bed practice for this job? 我有大量数据,所以我只想知道每次创建控制器和模型的对象都是这项工作的基础吗?

note : i don't create constructor in both class (model) 注意:我不会在两个类(模型)中都创建构造函数

Every time a new request is made php creates objects, and when php has finished processing destroys them. 每次发出新请求时,php都会创建对象,并且在php完成处理后会销毁它们。 Php does not keep anything in memory between requests, it has a "share nothing" approach. Php在两次请求之间不保留任何内容,而是采用“不共享”方法。 So no, you are not doing anything wrong. 所以不,您没有做错任何事情。

If you are calling an object multiple times in your code, for example a database connection class, and you only want one instance of that object throughout that request use singletons. 如果您在代码中多次调用一个对象,例如一个数据库连接类,并且在整个请求中您只希望该对象的一个​​实例使用单例。

class Singleton {

private static $instance;

   protected function __construct() 
   {
     //Do something, or don't
   }

   private function __clone() {}
   private function __wakeup() {}

   public static getInstance()
   {
       if (!static::$instance) {
           static::$instance = new Singleton();
       }
       return static::$instance;      
   }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM