$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