John Davidson

laravel - PHP Singleton returns different values with spl_object_hash

0 comments
Message:


I'm creating a singleton with PHP like this.


namespace App\Http\Controllers;

use App\classes\Test;

class TestController extends Controller
{
private static $test_obj;

private function __construct()
{
}

public static function get()
{
if (self::$test_obj === null) {
self::$test_obj = new Test();
}
return self::$test_obj;
}
}

Then I tried to test the code like this:


namespace App\Http\Controllers;

class MainController extends Controller
{
public function index()
{
$test_obj = TestController::get();
dd(spl_object_hash($test_obj));
}
}

At this point it returns different hash values. But it's supposed to return the same hash value since this is a Singleton right?


Note - spl_object_id() always returns the same object id though.



My Answer:
The issue here is that `spl_object_hash()` generates a unique identifier for an object based on its properties and state. Since you are creating a new instance of the `Test` class every time `TestController::get()` is called, the objects will have different properties and states, resulting in different hash values.

To make sure that `TestController::get()` always returns the same instance of the `Test` class (i.e., a true Singleton), you need to modify your code to ensure that only one instance of the `Test` class is created and returned. One way to achieve this is by using a static property to hold the instance of the `Test` class, like so:

php
namespace App\Http\Controllers;

use App\classes\Test;

class TestController extends Controller
{
private static $test_obj;

private function __construct()
{
}

public static function get()
{
if (self::$test_obj === null) {
self::$test_obj = new Test();
}
return self::$test_obj;
}
}


With this modification, `TestController::get()` will always return the same instance of the `Test` class, and calling `spl_object_hash(TestController::get())` multiple times should now return the same hash value.

Rate this post

3 of 5 based on 6382 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us