/    Sign up×
Community /Pin to ProfileBookmark

Trying to understand $this and classes?

I’m working on a site that I did not originally program. I’m new to working with PHP classes.

There is a class on this website called Reporting and an extension called main. An instance of main (called $main) is created in the index page (all other pages are an include of the index page). I can’t find any place that an instance of reporting is created.

What confuses me is from what I’ve read, it’s my understanding, in order to access a class you must create an instance of that class like this

[code=php]<$main = new main()[/code]

Then you can reference aspects of main like this

[code=php]$main->displaypage()[/code]

However there are places all over the code for this site where functions and variables in the reporting class are referenced using a variable called $this, like this

[code=php]$this->set_value(“type”,$_POST[‘type’])[/code]

from what I can tell $this is a special variable intended to be used within the class it’s self to reference things within the class.

Is this an appropriate use of $this?
everything seems to work ok (but I’m concenred there’s a problem I’m not seeing or I’ll break something if I don’t understand it)

In order for this to be working, does that mean $this was created as an instance of the reporting calss some where?

Any explination is appericates.

I’m including the classes and an example refernce of this outside the clase incase that will help.

[code=php]
class reporting {

var $errors = array(), $values = array(), $success = array();

function set_error ($name, $message) {
$this->errors[$name] = $message;
}

function get_error ($name) {
return isset($this->errors[$name]) ? $this->errors[$name] : false;
}

function set_success ($name, $message) {
$this->success[$name] = $message;
}

function get_success ($name) {
return isset($this->success[$name]) ? $this->success[$name] : false;
}

function set_value ($name, $value) {
$this->values[$name] = $value;
}

function get_value ($name) {
return isset($this->values[$name]) ? $this->values[$name] : false;
}

function has_errors ($error_list = false) {
if (is_array($error_list)) {
foreach ($error_list as $error) {
if ($this->errors[$error]) {
return true;
}
}
return false;
} else {
return (bool) count($this->errors);
}
}

function remove_error ($error) {
unset($this->errors[$error]);
}

function list_errors () {
return $this->errors;
}

}

class main extends reporting {

var $include, $logged_in, $user = array(), $unread_messages = 0, $options = array();

function main () {
@mysql_connect(MYSQL_HOSTNAME, MYSQL_USERNAME, MYSQL_PASSWORD) && @mysql_select_db(MYSQL_DATABASE) || die(‘<code><strong>MySQL Error:</strong> ‘ . mysql_error() . ‘</code>’);
session_start();
$this->authorize_user();
$this->clean_input();
$page = $_GET[‘page’];
if (preg_match(‘#^[a-z0-9-_]+$#’, $page)) {
if (file_exists(‘php/’ . ($file = ‘action.’ . $page . ‘.php’))) {
include $file;
}
}
$sql = “SELECT * FROM `options`”;
$q = mysql_query($sql);
while ($r = mysql_fetch_assoc($q)) {
$this->options[$r[‘option_name’]] = $r[‘option_value’];
}
if ($this->logged_in) {
$this->unread_messages = @mysql_num_rows(mysql_query(“SELECT `message_id` FROM `messages` WHERE `message_receiver_id` = ‘$this->user[user_id]’ AND `message_status` = ‘0’”));
}
if (preg_match(‘#^[a-z0-9-_]+$#’, $page)) {
if (file_exists(‘php/’ . ($file = ‘page.’ . $page . ‘.php’))) {
$this->include = $file;
} else {
$this->include = ‘page.error.php’;
}
} elseif (!strlen($page)) {
$this->include = ‘page.home.php’;
} else {
$this->include = ‘page.error.php’;
}
ob_start(array(&$this, ‘relatize’));
}

function get_option ($option_name) {
$sql = “SELECT * FROM `options` WHERE `option_name` = ‘$option_name'”;
$q = mysql_query($sql);
$r = mysql_fetch_assoc($q);
return unserialize($r[‘option_value’]);
}

function update_option ($option_name, $option_value) {
$option_value = is_array($option_value) ? serialize($option_value) : $option_value;
$sql = “UPDATE `options` SET `option_value` = ‘$option_value’ WHERE `option_name` = ‘$option_name'”;
$q = mysql_query($sql);
}

function display_page () {
include $this->include;
}

function allow_only ($types) {
if (is_array($types)) {
if (!in_array($this->user[‘user_type’], $types)) {
header(‘Location: ‘ . SITE_ROOT);
exit;
}
} else {
if ($this->user[‘user_type’] != $types) {
header(‘Location: ‘ . SITE_ROOT);
exit;
}
}
}

function authorize_user () {
if (valid_user_cookies()) {
$details = user_details($_COOKIE[‘user_id’]);
if ($details[‘user_password’] == $_COOKIE[‘user_pass’]) {
$this->logged_in = true;
$this->user = $details;
$sql = “UPDATE `users` SET `user_timestamp_last` = UNIX_TIMESTAMP(NOW()) WHERE `user_id` = ‘$details[user_id]'”;
mysql_query($sql);
} else {
$this->destroy_user();
}
}
}

function destroy_user () {
$time = time() – (60 * 60 * 24 * 7);
$parts = parse_url(SITE_ROOT);
setcookie(‘user_id’, ‘NULL’, $time, $parts[‘path’], $parts[‘host’]);
setcookie(‘user_pass’, ‘NULL’, $time, $parts[‘path’], $parts[‘host’]);
$this->logged_in = false;
}

function clean_input () {
foreach ($_GET as $key => $value) {
if (is_string($value)) {
$value = trim($value);
$_GET[$key] = get_magic_quotes_gpc() ? stripslashes($value) : $value;
}
}
foreach ($_POST as $key => $value) {
if (is_string($value)) {
$value = trim($value);
$_POST[$key] = get_magic_quotes_gpc() ? stripslashes($value) : $value;
}
}
}

function relatize ($buffer) {
return preg_replace(‘#(href|src|action)=”/#’, ‘\1=”‘ . SITE_ROOT, $buffer);
}

}

//from a file used to handle input from front end page

if (!is_uploaded_file($_FILES[‘file’][‘tmp_name’]) || !is_image($_FILES[‘file’][‘tmp_name’])) {
$this->set_error(‘file’, ‘Please select a valid image to upload.’);
} [/code]

to post a comment
PHP

5 Comments(s)

Copy linkTweet thisAlerts:
@chazzyMar 02.2009 — $this is simply a construct that gives a developer access to the current instance of the class in reference. it's not really an object on its own, but more of a way for the developer to let the code talk to itself.
Copy linkTweet thisAlerts:
@enad_26authorMar 02.2009 — $this is simply a construct that gives a developer access to the current instance of the class in reference.


I aperciate the response but I think I need more clarification.

What you just said above is consistant with everything I read in the PHP manual about classes and the $this construct. However what I'm still not understanding is how in the code I'm working with they used it outside the context of a class.

You explination and the PHP manual makes it sound like a $this should only be used with in the context of a class. And the whole point is you can't have an instance of that class with in the class so you need some why to refernce things with in the class.


So why am I seeing it outside of class? Being treated like an instance of a class? But I can't find where that instance was created.

how can it be used outside of a class? How does the system know which class $this reffers to if it's not with in a class?

I can only think of two possilities.

  • 1. The pervious programer did a really crazzy thing and intentionally created an instance of a class ( I assumeing reporting) and named that instance $this. And for some reason I can't find where he created it.


  • 2. There's other way to use $this where it acts as some sort of variable instance of a class, like it refernces that last created instance ( which seems like really vauge code as well).


  • So am I right that $this should only be used with in a class?

    IF so then any guesses how it's being used as a class instance?

    IF not then how is it used outside of a class? What's referncing and how is that defined?

    Thanks again for any help.
    Copy linkTweet thisAlerts:
    @NogDogMar 02.2009 — You should get a parse error if you try to assign anything to $this (at least you do in PHP5; I don't have a PHP4 version to test on), so it's hard to imagine how it could be used anywhere other than within a class definition. For instance, this script...
    [code=php]
    <?php
    class Foo
    {
    public function bar()
    {
    echo "Hello, World!";
    }
    }

    $this = new Foo();
    [/code]
    ...generates this error...

    Fatal error: Cannot re-assign $this in C:wampwwwtesttest.php on line 10
    [/quote]
    Copy linkTweet thisAlerts:
    @toicontienMar 02.2009 — The $this variable, when used inside a definition for a class method is a pointer to the current instance of that class. If using $this outside of a class method definition you might be able to assign a variable called $this:
    [code=php]<?php

    class TestClass {
    private $foo = '';

    public function __construct($foo) {
    // $this points to current instance of TestClass class
    $this->foo = $foo;
    }
    }

    // $this is a variable named $this
    $this = "foo";

    ?>[/code]


    I wonder if the code above generates an error? I guess I thought $this only had special meaning inside a class method definition as illustrated by the __construct function in the example above.

    enad_26, more than likely $this is being used inside a class method definition and you aren't realizing it.
    Copy linkTweet thisAlerts:
    @enad_26authorMar 02.2009 — I think I figured out what's going on here.

    toicontien-- I didn't see your post until after I figured it out. But you're right.

    It does apear assigning $this as an instance of a class does work in PHP 4. Seems like a very bad idea but it works. Maybe that's why they made it not work in PHP 5.

    But This site has worked on both PHP 5 and PHP 4. And when i tried to assign $this as an instance of a class on the PHP 5 server I got the same error.

    So I messed with this for about an hour....

    When suddenly the light bulb came on.

    This whole site is actually loaded through the same PHP file. That file calls a function within [B]a class [/B]to display all of the content that isn't reproduced on everypage.

    So because every other include is, included through a class any class functions must be refernced with $this instead of the instance name.

    Thank you all for your help.
    ×

    Success!

    Help @enad_26 spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 6.16,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @nearjob,
    tipped: article
    amount: 1000 SATS,

    tipper: @meenaratha,
    tipped: article
    amount: 1000 SATS,

    tipper: @meenaratha,
    tipped: article
    amount: 1000 SATS,
    )...