YogeshChauhan . com

$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 )
?>


amazon

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 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

How to create a pricing table using flex in CSS?CSSHow to Make a Simple Module with a Form and Menu Link in Drupal 7.x?DrupalINTERSECT and EXCEPT in PostgresPostgresHow to modify navigation menus in WordPress?WordPressLearn how to add Scroll Indicator using CSS and JavaScript?CSSCanvas Drawing in HTML5HTMLHow to scroll contents of HTML body horizontally and vertically using JavaScript?JavaScriptHow to Sort (Shuffle) an Array in Random Order in JavaScript?JavaScriptSolution to “TypeError: ‘x’ is not iterable” in Angular 9Angularinclude, include_once, require, require_once in PHPPHP@forward modules with a prefix in SCSS (Sass)SCSSHow to remove border from :visited image, link or button?CSS