PHP Constructor to Return a Null

PHP constructor to return a NULL

Assuming you're using PHP 5, you can throw an exception in the constructor:

class NotFoundException extends Exception {}

class User {
public function __construct($id) {
if (!$this->loadById($id)) {
throw new NotFoundException();
}
}
}

$this->LoggedUser = NULL;
if ($_SESSION['verbiste_user'] != false) {
try {
$this->LoggedUser = new User($_SESSION['verbiste_user']);
} catch (NotFoundException $e) {}
}

For clarity, you could wrap this in a static factory method:

class User {
public static function load($id) {
try {
return new User($id);
} catch (NotFoundException $unfe) {
return null;
}
}
// class body here...
}

$this->LoggedUser = NULL;
if ($_SESSION['verbiste_user'] != false)
$this->LoggedUser = User::load($_SESSION['verbiste_user']);

As an aside, some versions of PHP 4 allowed you to set $this to NULL inside the constructor but I don't think was ever officially sanctioned and the 'feature' was eventually removed.

Returning a value in constructor function of a class

Constructors don't get return values; they serve entirely to instantiate the class.

Without restructuring what you are already doing, you may consider using an exception here.

public function __construct ($identifier = NULL)
{
$this->emailAddress = $identifier;
$this->loadUser();
}

private function loadUser ()
{
// try to load the user
if (/* not able to load user */) {
throw new Exception('Unable to load user using identifier: ' . $this->identifier);
}
}

Now, you can create a new user in this fashion.

try {
$user = new User('user@example.com');
} catch (Exception $e) {
// unable to create the user using that id, handle the exception
}

Constructor with empty return

Actually, you may (no error will be occurred) use the return keyword in the __construct method but (you don't) that would be useless and won't return anything.

The __construct method doesn't create an object instance

It's not true that, the constructor creates the object instead, it's the new keyword which creates an object instance and returns the object. So, when we use something like this:

$obj = new SomeClass;

Then PHP creates the object returns the object instance. If this class contains any constructor method then this method is called by PHP after creation of that object instance. So, you can imagine, something similar:

class SomeClass {
public $prop = null;
public function init() {
$this->prop = 'SomeValue';
}
}

Now create the object and call the init method manually

$obj = new SomeClass;
$obj->init();

We created an instance of SomeClass and called the init methos manually but in the case of __construct method PHP calls the method automatically just after the creation of that object. So, we don't have to manually set the value to the prop property.

So, before the __construct method is called the object instance is created and without creating the object instance, the __construct method couldn't be called by PHP because $this refers to current object which is already created and if the object is not initialized then how can we call:

public function __construct()
{
$this->prop = 'SomeValue'; // $this refers to current object
}

The new keyword always returns an object instance:

Let's see this example:

class SomeClass {
public $prop = null;
public function __construct() {
$this->prop = 'SomeValue';
return $this->prop; // won't work
}

public function getProp() { ... }
}

Now check this:

$obj = new SomeClass;

If we were able to return a value from the constructor then how could we use the object instance using something like $obj->getProp() because logically it would contain SomeValue instead of the object reference/identifier, so it makes sense that PHP should not allow to return anything from the __construct method because this magic method get called automatically just after the creation of the object and we use new keyword to create the object instance that returned to us (into a variable) by the new keyword and if we return anything from the __construct method, it prevented by PHP and only an instance of the created object is returned if we didn't throw an exception explicitly.

To create an instance of a class, the new keyword must be used. An
object will always be created unless the object has a constructor
defined that throws an exception on error. Reference:PHP Manual

Though it's possible to use the return in the __constructor but it would be meaningless for example, check this:

class SomeClass {

public function __construct() {
return 'SomeValue'; // won't work
// or blank return
return;
}
}

Perhaps, you may do this (only for example):

class SomeClass {

public function __construct() {
if('some condition does not met then ...') return;
$this->prop = 'Prop is set';
}

public function doSomething(){
return $this->prop ? $this->prop : 'Sorry! Prop is set.';
}
}

Now try this:

$obj = new SomeClass;
echo $obj->doSomething();

If we just return before the second line in the constructor then the property won't be set otherwise the property will be set and doSomething method will output Prop is set. This may not a good way but for the example, I think this could be a valid code where return will stop execution of rest of the code. But it's not a good idea and maybe not required but for he sake of the example I can think the use of return, otherwise there is no need to use the return keyword in constructor and if someone uses it then it could be a personal choice of style or I don't know why.

Why constructor returns a null in Laravel 5.6

Constructors do not return values, their only purpose is to instantiate class instances.

If you want to fetch data and use it in your class, you can do something like:

class AdminController extends Controller
{
private $notifications;

public function __construct()
{
$this->notifications = Notification::where('read_status', 0)->get();
}
}

or

class AdminController extends Controller
{
private $notifications;

public function __construct()
{
$this->loadUnreadNotifications();
}

private function loadUnreadNotifications()
{
$this->notifications = Notification::where('read_status', 0)->get();
}
}

After which you can use $this->notifications in your other controller methods.

PHP Class __Constructor parameters are NULL once function call happened

For creating such complex objects, I suggest you to use Builder Design Pattern instead of assigning properties dynamically and directly.

Note: For better, you can add a layer of interface which Builder classes will implement. And you can have multiple Builder classes which generate different complex objects as per different use cases. Hope this make sense.

Try this code snippet here

<?php

class Builder {
public static function getMyClass($a, $b, $c) {
$myClass = MyClass::getInstance();
$myClass->setA($a);
$myClass->setB($b);
return $myClass;
}
}
class MyClass {
protected $a=0;
protected $b=0;

public static function getInstance() {
$myClass = new MyClass();
return $myClass;
}

function setA($a) {
$this->a = $a;
}

function setB($b) {
$this->b = $b;
}
}

$myClass = Builder::getMyClass("a", "b", "c");
print_r($myClass);

Explanation: In the above mentioned code we have a Builder class which is responsible for building such complex objects.

But still if you are still more towards dynamic assignment approach which nobody recommends, you can see this post

Constructor returning value?

Indeed you are correct. Nothing can be done with the return value of a constructor (aside from using the Object it created).

So no, you aren't missing anything, it's the developer who wrote that code who is.

It is technically possible to use return values from constructors, if you call the function directly

$obj->__construct();

That would allow you to use the constructor's return value. However, that is highly uncommon and fairly not recommended.

PHP Variable Instantiated in Constructor resetting to null

In PHP, if you want to call methods or use properties of the class you are in, you always have to use $this:

function __construct($feedUrl) {
$this->feedData = simplexml_load_file($feedUrl);
}

function parse() {
echo " \n begin parsing \n";
$rawArticles = $this->feedData->channel[0];
print_r($rawArticles);
...
}

Breaking the constructor

Nope, not possible; the new keyword always returns an instance of the class specified, no matter what you attempt to return from the constructor. This is because by the time your constructor is called, PHP has already finished allocating memory for the new object. In other words, the object already exists at that point (otherwise, there's no object on which to call the constructor at all).

You could raise errors or throw exceptions from the constructor instead, and handle those accordingly.

class Foo {
public function __construct() {
throw new Exception('Could not finish constructing');
}
}

try {
$object = new Foo();
} catch (Exception $e) {
echo $e->getMessage();
}

Accessing properties from parent class returning null while assigned in constructor

You are never calling your parent __construct(). Thus your mysqli is never created and is, yup null.

I know this is not codereview. But you should never use public properties. Just don't

You should also refractor your code to use Dependency Injection. Now, every cotnroller has a different mysqli object, instead of sharing the same resource.

Your methods are also doing to much, they do stuff, they handle errors, they echo output to the user, they do some redirecting, ... Keep it Stupid Simple, and go for Single responsbility



Related Topics



Leave a reply



Submit