Yogesh Chauhan's Blog

$this Keyword in PHP

in PHP on June 8, 2021

$this Keyword

PHP supports Object Oriented Programming.

Just like this keyword in JavaScript or some other programming languages, the $this keyword in PHP refers to the current object. It is only available inside the Class methods.

Take a look at this code:


<?php
class Car {
  public $model;
}
$tesla = new Car();
?>


The $this keyword is used when you want to change the value for the $model property.

Change the property value inside the class

To do so, we need to add a set_name() method and use $this keyword inside it.


<?php
class Car {
  public $model;
  function set_name($model) {
    $this->model = $model;
  }
}
$tesla = new Car();
$tesla->set_name("Tesla");

//print the object
print_r($tesla);
//Car Object ( [model] => Tesla )
?>


That’s not the only way to change the value for the object property though.


Change the property value outside of the class

To do so, we need to add a set_name() method and use $this keyword inside it.


<?php
class Car {
  public $model;
}

$tesla = new Car();
$tesla->name = "Tesla";

//print the object
print_r($tesla);
//Car Object ( [model] => Tesla )
?>



Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
A list of wp-cli commands to use via SSHWordPressKilling A Project Part 3: How can an organization ensure that a doomed project is killed as early as possible?MiscellaneousComponents and Props in ReactReactAn Example of Cross-site Scripting (XSS) Attack in PHP and How to Avoid It?PHPRecursive WITH Queries in Postgres (Common Table Expressions)PostgresLearn to Implement Estimated Reading Time using PHP Part 1: The BasicsPHPHow to use GROUPING SETS to boost GROUP BY queries in Postgres?Postgresrandom function in SCSS (Sass)SCSSAll different methods for accessing elements in the DOM using JavaScriptJavaScriptHow to use PHPMailer to send an Email via Gmail SMTP Server?PHP5 Steps to Create a Line using Canvas Tag in HTML5HTMLModules and its Core features in JavaScriptJavaScript