-3

I am new in OOP PHP. Why do we have to use $this reference, when the code is working without it too?

If I delete both $this (before ->sql) from this code fragment, the modification is work as well. Although I read about it, I still don't understand what is $this in the given method.

class blogs{

    private $servername = "localhost";
    private $username = "root";
    private $password = "";
    private $dbname = "asd";
    private $conn = "";
    private $result = "";
    private $row = "";
    private $sql = "";

    public function cmd_update(){
        $this->sql = "UPDATE 
                blogs 
                SET
                `name` = '".$_GET['input_name']."',
                `date` = '".date('Y-m-d H:m:s')."',
                WHERE
                id = ".$_GET['input_modifying_id']."        
        ";

        if ($this->conn->query($this->sql) === TRUE) {
            echo "Successfully modified!";
        } else {
            echo "Modifying Unsuccessful!";
        }       
    }
j08691
  • 204,283
  • 31
  • 260
  • 272
  • 1
    `$this` is used to reference the class you're in. If you do `$this->foo = 'bar';`, you can access `$this->foo` from other methods (and from outside the class, if it is set as `public`), while variables without `$this` it will be a local variable that will only be accessible in the scope of that specific method. So `$this->foo` and `$foo` are two different variables in different scopes. – M. Eriksson Dec 11 '18 at 14:26
  • `$this` is the current instance of the class. If, for example, you had multiple `Blog` instances, each one could have its own `$this->title` that doesn't interfere with *other* `Blog` instances. – ceejayoz Dec 11 '18 at 14:27
  • 1
    http://php.net/manual/en/language.oop5.visibility.php – MonkeyZeus Dec 11 '18 at 14:27
  • By removing `$this` in front of `$this->sql`, you're turning that into a privately scoped variable which is not accessible within the class (outside of `cmd_update`). By specifying `$this->sql`, you're assigning it to the member variable instead. – BenM Dec 11 '18 at 14:27
  • see the example in [this answer](https://stackoverflow.com/a/28689642/7393478). Omitting `$this` can lead to confusing class properties with local variables – Kaddath Dec 11 '18 at 14:28
  • 2
    Side note: Seeing that you appear to be a new coder, your code is open to an SQL injection. Best you use a prepared statement. You wouldn't want your database to be compromised or deleted one day. – Funk Forty Niner Dec 11 '18 at 14:32
  • In the above code, there's also no reason to add `$sql` as a class property and using `$this` for it. – M. Eriksson Dec 11 '18 at 14:36
  • Yes if you replace `$this->sql = "...";` with `$sql = "...";` of course it will work. Thats because the text string for the query is only required until it is used. I would not have made `$sql` a class property anyway. Its only required to hold the SQL syntax you execute the next line in that method – RiggsFolly Dec 11 '18 at 14:36
  • But you do want to keep one `$con` that can be used by all the methods within this class. So keeping that as a object property does make sense – RiggsFolly Dec 11 '18 at 14:38

2 Answers2

4

$this refers to the current object - in this case, $this is shorthand for the blogs class.

Let's take this example class:

class Foo
{
    protected $a;

    public function __construct($a)
    {
        $this->a = $a;
    }

    public function getA()
    {
        return $this->a;
    }
}

Here I'm simply assigning $a to whatever gets passed to a new Foo instance and creating a public-accessible function to return $a.

We use $this to refer to what we're currently in, $this->a is the protected $a.

This is a really handy feature for developers as it means we don't have to create our own way of getting the instance without redeclaration. It also means we can use templating for easier use. E.g.

class Foo
{
    public function sayHi()
    {
        return 'hello world';
    }
}

and

class Bar extends Foo
{}

because public functions are well.. public we can access parent classes with $this:

<?php
    $bar = new Bar();
    echo $bar->sayHi(); # will output hello world

It also means we can create a set of generic functions and properties relating to the object to allow more dynamic code. Take these blogs:

title = hello world
content = hello world
img = /path/to/img.jpg

title = what we did last summer
content = played in the park
img = /path/to/another/img.jpg

We can have a blog class like this:

class GenericController
{
    # pretend we've done some PDO set up here where we set new PDO to $this->pdo
    public function load($id)
    {
        $sql = 'SELECT * FROM `blogs` WHERE `id` = :id';
        $res = $this->pdo->prepare($sql);
        $res->execute(array(':id' => $id));

        return (object) $res->fetch(PDO::FETCH_ASSOC);
    }
}

class Blog extends GenericController
{
    protected $id;
    protected $data;

    public function __construct($id)
    {
        $this->id = $id;
    }

    protected function loadData()
    {
        $this->data = $this->load($this->id);
    }

    public function getTitle()
    {
        return $this->data->title;
    }

    public function getContent()
    {
        return $this->data->content;
    }

    public function getImg()
    {
        return $this->data->img
    }
}

$blogOne = new Blog(1);
$blogTwo = new Blog(2);

echo $blogOne->getTitle(); # will output hello world
echo $blogTwo->getTitle(); # will output what we did last summer

further reading:

For MySQL Injection reasons (your code is currently open to said injection):

PDO
PDO Prepared Statements

For OOP:

The Basics
Visibility

And $this from the docs itself (can be found via The Basics link):

The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object). As of PHP 7.0.0 calling a non-static method statically from an incompatible context results in $this being undefined inside the method

treyBake
  • 6,440
  • 6
  • 26
  • 57
0

$this is a reference of current calling object or we can say that object in use. When you work with multiple instance of class your code base will be manageable for different instances. Also the visibility allows that what you want to keep private or public. And $this will work throughout the object life once you set you can accept anywhere in the object/class scope not limited to the function.

Rohit Rasela
  • 425
  • 3
  • 6