Php use this in constructor

PHP $this

Summary: in this tutorial, you will learn about PHP $this keyword and how to use $this inside a class to reference the current object.

What is $this in PHP?

In PHP, $this keyword references the current object of the class. The $this keyword allows you to access the properties and methods of the current object within the class using the object operator ( -> ):

$this->property $this->method()Code language: PHP (php)

The $this keyword is only available within a class. It doesn’t exist outside of the class. If you attempt to use the $this outside of a class, you’ll get an error.

When you access an object property using the $this keyword, you use the $ with the this keyword only. And you don’t use the $ with the property name. For example:

$this->balanceCode language: PHP (php)

The following shows the BankAccount class:

 class BankAccount < public $accountNumber; public $balance; public function deposit($amount) < if ($amount > 0) < $this->balance += $amount; > > public function withdraw($amount) < if ($amount $this->balance) < $this->balance -= $amount; return true; > return false; > >Code language: PHP (php)

In this example, we access the balance property via the $this keyword inside the deposit() and withdraw() methods.

Читайте также:  Html design tool online

Chaining methods

First, create a new BankAccount object:

// create a new account object $account = new BankAccount(); $account->accountNumber = 1; $account->balance = 100;Code language: PHP (php)

Second, call the deposit() method three times to deposit different amounts of money:

$account->deposit(100); $account->deposit(200); $account->deposit(300);Code language: PHP (php)

This code is quite verbose. It would be more concise and expressive if you can write these statements using a single statement like this:

$account->deposit(100) ->deposit(200) ->deposit(300);Code language: PHP (php)

This technique is called method chaining.

To form the chain, the deposit() method needs to return a BankAccount object, which is the $this inside the BankAccount class like this:

 class BankAccount < public $accountNumber; public $balance; public function deposit($amount) < if ($amount > 0) < $this->balance += $amount; > return $this; > public function withdraw($amount) < if ($amount $this->balance) < $this->balance -= $amount; return true; > return false; > >Code language: PHP (php)

The deposit() returns the $this which is the current object of the BankAccount class. Therefore, you can call any public method of the BankAccount class.

The following example calls the deposit() method first and then the withdraw() method in a single statement:

$account->deposit(100) ->withdraw(150);Code language: PHP (php)

It’s equivalent to the following:

$account->deposit(100); $account->withdraw(150);Code language: PHP (php)

Summary

  • PHP $this keyword references the current object of the class. It’s only available within the class.
  • Do use the method chaining by returning $this from a method to make the code more concise.

Источник

Example code for returning ‘this’ in the PHP constructor

Consider this example and compare it to the following scenario. If the constructor could return a value, then it would logically contain the value rather than the object reference, which is why the method should not allow for any returns. The constructor is a magic method that is called automatically after the object instance is created using the «new» keyword. If anything is returned from the constructor method, it is prevented by the «new» keyword and only the object instance is returned. The object instance must be created before the constructor method can be called, which is why the «new» keyword is used to create and return the object instance. The «this» keyword refers to the current object, which is already created, so if the object is not initialized, we cannot call the constructor method. It is important to note that the «new» keyword always returns an object instance.

Redirect/Return inside the Constructor

Based on my observation, this is not a good approach. Middleware is utilized for tasks that need to be performed before the controller initialization, such as authentication.

If you need to perform an admin check or similar tasks, it is possible to develop your own middleware. To learn more, refer to the provided link.

Php8 constructor Code Example, Get code examples like «php8 constructor» instantly right from your google search results with the Grepper Chrome Extension.

Constructor with empty return

The return keyword can be used in the __construct method without causing any errors, but it is pointless as it doesn’t produce any output.

The __construct method doesn’t create an object instance

Contrary to popular belief, the object is not created by the constructor. Rather, it is the new keyword that is responsible for creating an instance of the object and returning it. Therefore, when we utilize code such as this:

Upon execution, PHP instantiates an object which is then returned as an instance. Should constructor be present within the class, PHP will invoke it after the object instance has been created. This process can be likened to something similar.

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

Instantiate the entity and manually invoke the init function.

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

An instance of SomeClass was generated and the init method was manually invoked, while the __construct method automatically triggers the PHP method upon object creation. Consequently, there is no need to set the value of the prop property manually.

Prior to invoking the __construct method, an object instance is generated. Without this instance, __construct cannot be invoked by PHP , as $this pertains to the already created object. If the object is not initialized, it is impossible to make the call.

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

The new keyword always returns an object instance:

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

Since the constructor is automatically called upon object creation using the «new» keyword, it is not logical to return a value from it. If we were to do so, the object instance would contain the returned value instead of its reference/identifier. Therefore, it makes sense that the constructor method should not allow for return values. If we attempt to return something from the constructor method, it will be prevented by the language syntax. Instead, we use the «new» keyword to create the object instance and assign it to a variable. If no exception is thrown, only the instance of the created object is returned.

The instantiation of a class requires the utilization of the new keyword, which results in the creation of an object, unless a constructor with an error-throwing mechanism is defined. This information can be found in the PHP Manual.

While the return can be employed in the __constructor , it would hold no significance, as demonstrated below:

It is possible that you could do this as an illustration.

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.'; > > 
$obj = new SomeClass; echo $obj->doSomething(); 

To prevent the property from being set, we can exit before reaching the second line in constructor . Otherwise, if we proceed, the property will be set and the doSomething method will produce the output Prop is set . Although this may not be the best approach, it could be a valid code for this example. Using the return keyword to halt the execution of the remaining code is not recommended, and may not even be necessary. If someone chooses to use the return keyword in the constructor, it may simply be a matter of personal style.

Typically, this indicates inadequate execution as a constructor solely produces an object of its class and does not «return» anything else.

PHP — The __construct Code Example, Get code examples like «PHP — The __construct» instantly right from your google search results with the Grepper Chrome Extension. Follow. GREPPER; SEARCH SNIPPETS; PRICING; FAQ; USAGE DOCS ; INSTALL GREPPER; Log In; All Languages >> PHP >> PHP — The __construct “PHP — The __construct” Code Answer’s. php …

How to return errors from constructor method in PHP

It is recommended to utilize a distinct class for the purpose of validating form data. Check out the following article for further guidance.

Another possibility is to include a method named valid() in the User class.

Subsequently, utilize the function as required to authenticate the information.

$user = new User(. ); if($user->valid())< echo 'the information is valid.'; >else

PHP OOP Constructor, PHP — The __construct Function A constructor allows you to initialize an object’s properties upon creation of the object. If you create a __construct () function, PHP will automatically call this function when you create an object from a class. Notice that the construct function starts with two underscores (__)!

Return false from __constructor

Constructors do not yield return values. However, if you need to obtain a certain outcome from a constructor, there are a few options available.

To obtain a return value, it is recommended to employ a method that performs the necessary operations, commonly referred to as init() .

public static function init( $host, $username, $password, $connection_type )< //setting the classes vars $this->host = $host; $this->username = $username; $this->password = $password; $this->connection_type = $connection_type; //now set the connection into this classes connection $this->connection = $this->connect(); //check the connection was set else return false if($this->connection === false) < return false; >> $ftp_sftp = ftp_sftp::init(); 

Save the output in a class property and verify its content subsequent to invoking the constructor.

function __construct( $host, $username, $password, $connection_type )< //setting the classes vars $this->host = $host; $this->username = $username; $this->password = $password; $this->connection_type = $connection_type; //now set the connection into this classes connection $this->connection = $this->connect(); > $ftp_sftp = new ftp_sftp( $host, $uname, $pword, $connection_type ); if ($ftp_sftp->connection !== false) < // do something >

By causing an exception in your connect() method, the program’s execution will be halted and redirected to your catch block.

private method contect() < // connection failed throw new Exception('connection failed!'); >try < $ftp_sftp = new ftp_sftp( $host, $uname, $pword, $connection_type ); >catch (Exception $e) < // do something >

In cases where constructors need to return values, throwing an exception is a possible solution.

You have the option to declare a variable within a try-catch clause.

It is possible to test your connect() method by creating an object outside and using it directly.

$ftp_sftp = new ftp_sftp( $host, $uname, $pword, $connection_type ); $ftp_sftp->connect(); 

Construct — PHP: using $this in constructor, It doesn’t work. You can’t unset or fundamentally alter the object that is being created in the constructor. You can also not set a return value. All you can do is set the object’s properties. One way to get around this is having a separate «factory» class or function, that checks the condition and returns a new instance …

Источник

Оцените статью