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 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to calculate elapsed time in JavaScript?JavaScriptHow to undo Git Commits on Pantheon?MiscellaneousHow to create and store JSON objects in localStorage using JavaScript?JavaScriptHow to create a blurry text effect using CSS?CSSHow to Use ROLLUP Operator in SQL and MySQL?SQL/MySQLURL paths in DrupalDrupalALTER DATABASE in PostgreSQLPostgresHow to apply style only to first child and/or only to children other than the first child?CSSHow to set up the local environment and workspace for Angular development?AngularHow to Install PHP composer in Mac OS Catalina?PHPSELF JOIN in PostgresPostgresThe basics of @import rule in SCSS (Sass)SCSS