[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 409
  • Last Modified:

How to define my variable when inside of a php class??

Can anyone tell me why I am getting this error message?

Fatal error: Using $this when not in object context

I am inside of a class so I must use $this->table, not $table, right??
function count_all() {
	global $database;
	$sql = "SELECT COUNT(*) FROM " . $this->table;
	$result = $database->query($sql);
	$row = $database->fetch_array($result);
	return array_shift($row);
}

Open in new window

0
FairyBusiness
Asked:
FairyBusiness
  • 5
  • 5
1 Solution
 
Beverley PortlockCommented:
The problem is this line

$sql = "SELECT COUNT(*) FROM " . $this->table;

can only be used like this INSIDE a class. Since you are getting that error message, PHP thinks that you are not in a class.

Can you post the whole class  that function count_all is part of?
0
 
FairyBusinessAuthor Commented:
Here is the Image class:


<?php
require_once 'includes/database.php';
require_once 'includes/DBobject.php';

class Image { 

protected $table = "images";
// list of database fields
protected  $db_fields = array('id', 'filename', 'type', 'size', 'caption');
var $id;
var $filename;
var $type;
var $size;
var $caption;
private $temp_path;
protected $upload_dir = "images";
var $errors = array();

// Common Databaes Methods
/*
$upload_errors = array(
	// http://www.php.net/manual/en/features.file-upload.errors.php
	UPLOAD_ERR_OK			=> "No errors.",
	UPLOAD_ERR_INI_SIZE		=> "Larger than upload_max_filesize.",
	UPLOAD_ERR_FORM_SIZE	=> "Larger than form MAX_FILE_SIZE.",
	UPLOAD_ERR_PARTIAL		=> "Partial upload.",
	UPLOAD_ERR_NO_FILE		=> "No file.",
	UPLOAD_ERR_NO_TMP_DIR	=> "No temporary directory.",
	UPLOAD_ERR_CANT_WRITE	=> "Can't write to disk.",
	UPLOAD_ERR_EXTENSION	=> "File upload stopped by extension."
);
*/
// Pass in $_FILE(['uploaded_file']) as an argument
function attach_file($file) {
	// Perform error checking on the form parameters
	if(!$file || empty($file) || !is_array($file)) {
		// error: nothing uploaded or wrong argument usage
		$this->errors[] = "No file was uploaded.";
		return false;
	}
	elseif($file['error'] != 0) {
		// error: report what PHP says went wrong
		$this->errors[] = $this->upload_errors[$file['error']];
		return false;
	}
	else {
		// Set object attributes to the form paramenters
		$this->temp_path = $file['tmp_name'];
		$this->filename	 = basename($file['name']);
		$this->type		 = $file['type'];
		$this->size	 	 = $file['size'];
		// Don't worry about saving anything to the database yet
		return true;
	}
}
/*
public function save() {
	parent::save();
}
*/
function image_path() {
	return $this->upload_dir.DS.$this->filename;
}
function size_as_text() {
	if($this->size < 1024) {
		return "{$tihs->size} bytes";
	}
	elseif($this->size < 1048576) {
		$size_kb = round($this->size/1024);
		return "{$size_kb} KB";
	}
	else {
		$size_mb = round($this->size/1048576, 1);
		return "{$size_mb} MB";
	}
}
function save() {
	// A new record won't have an id yet
	if(isset($this->id)) {
	// really just to update the caption
		$this->update();
	}
	else {
	// make sure there are no errors (can't save if there are pre-existing errors)
	if(!empty($this->errors)) {
		return false;
	}
	// make sure the caption is not too long for the DB
	if(strlen($this->caption) >= 255) {
		$this->error[] = "The caption can only be 255 characters long.";
		return false;
	}
	// can't save without filename and temp location
	if(empty($this->filename) || empty($this->temp_path)) {
		$this->errors[] = "The file location was not availabe." . var_dump($this->temp_path) . var_dump($this->filename);;
		return false;
	}
	// determine the target_path
	$target_path = $this->upload_dir.DS.$this->filename;
	// make sure a file doesn't already exist in the target location
	if(file_exists($target_path)) {
		$this->errors[] = "The file {$this->filename} already exisits.";
		return false;
	}
	// attempt to move the file
	if(move_uploaded_file($this->temp_path, $target_path)) {
		// success
		// save a corresponding entry to the database
		if($this->create()) {
		// done with temp_path, the file isn't there anymore
			unset($this->temp_path);
			return true;
		}
	}
	else {
		// file was not moved
		$this->errors[] = "The file upload failed, possibly due to incorrect permissions on the upload folder.";
		return false;
	}
  }
}
function display_images() {
	foreach($images as $image):
		echo "<a href=\"photo.php?id=" . $this->id . "\">";
		echo "<img src=\"" . $this->image_path() . "\" /></a>";
		echo $this->caption;
	endforeach;
}
function count_all() {
	global $database;
	$sql = "SELECT COUNT(*) FROM " . $this->table;
	$result = $database->query($sql);
	$row = $database->fetch_array($result);
	return array_shift($row);
}
// Made protected so that one cannot call this directly, must use save()
protected function create() {
	global $database;
	$attributes = $this->sanitized_attributes();
	$adjust = "ALTER TABLE users AUTO_INCREMENT = 1";
	$sql = "INSERT INTO " . self::$table . " (";
	$sql .= join(", ", array_keys($attributes));
	$sql .= ") VALUES ('";
	$sql .= join("', '", array_values($attributes));
	$sql .= "')";
	$noGaps = $database->query($adjust);
	if($database->query($sql)) {
		$this->id = $database->insert_id(); // Update the variable
		return true;
	}
	else {
		return false;
	}
}
public function destroy() {
	// first remove from the database entry
	if($this->delete()) {
		// then remove the file
		$target_path = $this->image_path();
		return unlink($target_path) ? true : false;
	}
	else {
		// database delete failed
		return false;
	}
}
protected function update() {
	global $database;
	$attributes = $this->sanitized_attributes();
	foreach($attributes as $key => $value) {
		$attribute_pairs[] = "{$key}='{$value}'";
	}
	$sql = "Update " . self::$table_name . " SET ";
	$sql .= join(", ", $attributes_pairs);
	$sql .= " WHERE id=" . $database->clean_strings($this->id);
	$database->query($sql);
	return ($database->affected_rows() == 1) ? true : false;
}
protected function delete() {
	global $database;
	$sql = "DELETE FROM " . self::$table;
	$sql .= " WHERE id=" . $database->clean_strings($this->id);
	$sql .= " LIMIT 1";
	$database->query($sql);
	return ($database->affected_rows() == 1) ? true : false;
}
} // End class Images
?>

Open in new window

0
 
FairyBusinessAuthor Commented:
Fatal error: Using $this when not in object context in /hermes/web09c/b2950/moo.auroriellacom/includes/images.php on line 131
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
Marco GasiFreelancerCommented:
You should have instantiated your class somewhere this way

$myclass = new Image();

so in your query just write

$sql = "SELECT COUNT(*) FROM " . $myclass->table;

Maybe you also have to add a reference to that class as a global variable in your function
function count_all() {
	global $database;
        global $myclass;
	$sql = "SELECT COUNT(*) FROM " . $myclass->table;
	$result = $database->query($sql);
	$row = $database->fetch_array($result);
	return array_shift($row);
}

Open in new window

but I'm not sure about this.

Cheers
0
 
FairyBusinessAuthor Commented:
well, on my image_tests.php page I instantiate my class like this:

$images = new Image();
$images->display_images();

and then I call the next function.  So instead of $this-> I should use  $Image-> inside of the Image class??
0
 
Marco GasiFreelancerCommented:
I'm sorry for misreading. No, forget what I said, please. Let me think about...
0
 
Marco GasiFreelancerCommented:
I see in other functions you're using self::$table: why here you use $this->table? I don't find in your code any about it...
0
 
FairyBusinessAuthor Commented:
I fixed it.  That was left over from when I had made some functions static, but I did away with that.

For my page class I am getting this error now:

Parse error: syntax error, unexpected T_VARIABLE in /hermes/web09c/b2950/moo.auroriellacom/includes/page.php on line 64

Why do I keep getting errors over the simple $this-> ???
<?php
require_once 'includes/database.php';
require_once 'includes/DBobject.php';

class Page { 

var $current_page;
var $per_page;
var $total_count;
protected $table = "images";

public function __construct($current_pg=1, $per_page=20, $total_count=0) {
	$this->current_page = (int)$current_pg;
	$this->per_page = (int)$per_page;
	$this->total_count = (int)$total_count;
}
public function offset() {
	return ($this->current_page - 1) * $this->per_page;
}
public function total_pages() {
	// ceil because you want to always around up 
	return ceil($this->total_count/$this->per_page); 
}
public function previous_page() {
	// ceil because you want to always around up 
	return $this->current_page - 1; 
}
public function next_page() {
	// ceil because you want to always around up 
	return $this->current_page + 1; 
}
public function has_previous_page() {
	// ceil because you want to always around up 
	return $this->previous_page() >= 1 ? true : false;
}
public function has_next_page() {
	// ceil because you want to always around up 
	return $this->next_page() <= $this->total_pages() ? true : false;
}
// Pass in $_FILE(['uploaded_file']) as an argument
public function attach_file($file) {
	// Perform error checking on the form parameters
	if(!$file || empty($file) || !is_array($file)) {
		// error: nothing uploaded or wrong argument usage
		$this->errors[] = "No file was uploaded.";
		return false;
	}
	elseif($file['error'] != 0) {
		// error: report what PHP says went wrong
		$this->errors[] = $this->upload_errors[$file['error']];
		return false;
	}
	else {
		// Set object attributes to the form paramenters
		$this->temp_path = $file['tmp_name'];
		$this->filename	 = basename($file['name']);
		$this->type		 = $file['type'];
		$this->size	 	 = $file['size'];
		// Don't worry about saving anything to the database yet
		return true;
	}
}
function get_pages() {
	$sql = "SELECT * FROM " $this->table;
	$sql .= " LIMIT " . $this->per_page;
	$sql .= " OFFSET " . $page->offset();
	$images = $db_object->find_by_sql($sql);
	$images = $database->query($sql);
	return $images;
}
public static function count_all() {
	global $database;
	$sql = "SELECT COUNT(*) FROM " $this->table;
	$result = $database->query($sql);
	$row = $database->fetch_array($result);
	return array_shift($row);
}
} // End class Page
?>

Open in new window

0
 
Marco GasiFreelancerCommented:
You forgot the concatenation dot ;-)
0
 
Marco GasiFreelancerCommented:
You wrote

$sql = "SELECT * FROM " $this->table;

instead of

$sql = "SELECT * FROM " . $this->table;
0
 
FairyBusinessAuthor Commented:
Thanks! :)
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 5
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now