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 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #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

#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 #Jan 14 How to display a student’s individual transcript in Colleague? #Jan 11 How to install PuTTY on a MacOS?
You might also like these
Forcing the domain to serve securely using HTTPSMiscellaneousHow to delete a local and a remote Git branches?Miscellaneousadd_filter function in WordPressWordPressHow to change HTML content on click using JavaScript?JavaScriptHigher Order Functions in JavaScript with ExamplesJavaScriptHow JavaScript classes allows us to do less typing (syntactic sugar)?JavaScript5 Ways to Loop Through JavaScript ArraysJavaScriptHow to create a flip effect with CSS?CSSOptional arguments, Default parameters and REST parameters in JavaScriptJavaScriptUse inline if to make a shorter conditional syntax in ReactReactLearn to create profile card using HTML and CSSCSSHow to create a horizontal scrolling menu with and without flex using CSS (or SCSS)?CSS