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 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

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
Variables and Distance Functions in SCSS (Sass)SCSSHere’s what we can do with PHP date() functionPHPHow to install Gulp with WordPress?WordPressA simple example on grid ‘auto-fill’ vs ‘auto-fit’CSSWhat does Containment mean in React?ReactSelector Lists and Combinators in SCSS (Sass)SCSS5 Key Principles Of Good Website UsabilityUI/UXHow to apply style only to first child and/or only to children other than the first child?CSS4 advanced ways to search ColleagueColleagueThe ALPHA function in Envision BasicEnvision BasicResponsive Masonry Grid using CSS columns PropertyCSSHow to create HTML elements with ID and class using JavaScript?HTML