0


I have a page (index) that acts as an entry point to my application.That page will call function sayHi() and display something based on value (normally the function will do a DB query and display information). I want to know the best method to use.
First method : a new object will always be created each time a user does a request (or page refresh).So is it problematic for page performance (or memory) ?
Second method : let's say we have 2 users that query an index page at exactly same time (with different value), what will happen (race condition) ?
Index page

<?php require_once('firstTest.php'); $value = $_GET['params']; // 1st method $first = new FirstTest(); $first->sayHi($value); // 2nd method $second = FirstTest::getInstance(); $second->sayHi($value); 

firstTest class:

class FirstTest extends Singleton { public function sayHi($value) { echo 'value is : ' .$value; } } 

firstTest (2nd method)

class FirstTest { public function sayHi($value) { echo 'value is : ' . $value; } } 

singleton class

abstract class Singleton { protected static $instance; protected final function __construct(){} protected final function __clone(){} public final function __sleep(){ throw new Exception('cannot serialize'); } public static function getInstance(){ if (self::$instance === NULL) self::$instance = new self(); return self::$instance; } } 

1 Answer 1

1

In PHP every request is (at least logically) a different process and your variables are all created and destroyed within that request.

If you need to instantiate FirstTest many times within the same request, of course you will get better performance and less memory usage by using a singleton than by instantiating that many new objects. But as far as I understand you just instantiate it once anyway, so it makes no difference.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, so I will go for first method

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.