Solved

What does this mean in OOP for PHP?

Posted on 2013-01-18
10
381 Views
Last Modified: 2013-01-19
I'm slowly making my way through the basics of OOP and I've come across something that I've yet to see in the tutorials that I'm referring to.

In every example thus far, when you see something like this:

$this->featured_image="", it's referring to a variable of some sort that's generated in a query or something like that.

Here's what I'm looking at:

I'm getting an error that says, "Catchable fatal error: Object of class SingleImage could not be converted to string in /mnt/vhosts/heavydutylighting.com/httpdocs/cms/mod_product/product.inc.php on line 174"

Line 174 is this: WHERE  uuid='".$this-> featured_image_index_1." from the following query:

DELETE FROM single_images
WHERE  uuid='".$this-> featured_image_index_1."'
OR uuid='".$this-> featured_image_index_2."'
OR uuid='".$this->diagram_thumb."'
OR uuid='".$this->diagram_large."'
");

So when I got to the class SingleImage file and look for where featured_image_index_1 is being defined, thinking I'm getting the error because there's no variable retrieved for the query to work, there is no reference to featured_index_image_1 at all. I've got the code attached.

My question is: Is the error that I'm getting being generated because there is no value for $this->featured_image_index_1? Is that why I'm getting the error that says it can't be converted to a string?
0
Comment
Question by:brucegust
  • 4
  • 3
  • 2
  • +1
10 Comments
 
LVL 34

Assisted Solution

by:gr8gonzo
gr8gonzo earned 250 total points
ID: 38794626
No, this is because it actually IS finding a variable / value that you have tried to use as if it were a string, but the variable you're trying to echo is actually an instance of an object called SingleImage, not a string. PHP tries to convert things to strings automatically when it thinks you want a string and will throw an error when it cannot do that.

For example, this should say "Object of class HumanBeing could not be converted to string":

<?php
$x = new HumanBeing();
echo $x;

class HumanBeing
{
}
?>
0
 

Author Comment

by:brucegust
ID: 38794861
OK, gonzo, let me explain back to you what you're saying just so I understand "what" as well as "why."

First off, here's the single image.inc.php file where the SingleImage class is being referenced:
<?php


class SingleImage{

	var $uuid,$file_name,$size,$isnew,$imagename,$file_path,$filehaschanged;
	
	var $inputname;

	function SingleImage($inputname=""){
	
	$this->inputname=$inputname;
	
	$this->uuid=CreateId();
	$this->file_name="";
	$this->size=0;
	$this->isnew=1;
	$this->imagename="NO IMAGE SELECTED";
	$this->file_path="temp".$_SESSION['path_sep'];
	$this->filehaschanged=0;
	}

	

	function Load($uuid){
	
	if($uuid){
	$data= SqlQuery("","select * from single_images where uuid ='".$uuid."';");
	
	$line=mysql_fetch_array($data);
		
	$this->uuid=$line["uuid"];
	$this->file_name=$line["file_name"];
	$this->size=$line["size"];
	$this->imagename=$line["name"];
	$this->file_path="image_bank/single_images".$_SESSION['path_sep'];
	$this->isnew=0;
	//I'm adding some additional lines here in light of the fact that I'm getting a fatal error every time I attempt to delete an image saying that the object could not be converted
	//into a string
	}
	}

	function DeleteImage(){
		//this funtion will delete the selected pdf object from the database
		
		//delete files
		if($this->file_name != ""){
			if(file_exists(realpath($this->file_path.$this->file_name))){
				unlink(realpath($this->file_path.$this->file_name));
			}
		
		
		}
		
		// delet from database
		$sql="delete from parent_image_xref where image_uuid='".$this->uuid."';";
		SqlQuery("",$sql);
		
		SqlQuery("","delete from single_images where uuid='".$this->uuid."';");
	
	}

	function Save($parent_uuid){
	//this will save the specific item to the database
	//echo "SAVING";
		// if is new then insert into database and copy file to new location, delete old file
		if($this->isnew){
		if($this->file_name != "" and $this->imagename != "NO IMAGE SELECTED" ){

		
			//copy file to its new location in the pdf directory
			if($this->file_name != ""){
				$target_path= "image_bank/single_images";
			
				if(file_exists(realpath("temp/".$this->file_name))){
				
					//copy file to targetlocation
					$name= $this->file_name;
					
							$count=1;
						
							while(file_exists(realpath($target_path.$_SESSION['path_sep'].$name))){
								//file already exists
								$name=$count."_".strtoupper(str_replace(" ","_",str_replace("'","",$this->file_name)));
								$count++;
							}
					
					
						 copy(realpath("temp/".$this->file_name),realpath($target_path).$_SESSION['path_sep'].$name);
						
						
					unlink(realpath("temp/".$this->file_name));
					$this->file_name=$name;
				
				}
			}
			SqlQuery("","insert into single_images set uuid ='".$this->uuid."', file_name='".$this->file_name."', size='".$this->size."', name='".$this->imagename."'");
			//SqlQuery("","insert into parent_image_xref set parent_uuid='".$parent_uuid."', image_uuid='".$this->uuid."' ");
			
		}
		}else{
		// item not new so update the database with the replacement info
		
		//copy the file from temp if the file has changed
					if($this->filehaschanged){
						if($this->file_name != ""){
							$target_path= "image_bank/single_images";
						
							if(file_exists(realpath("temp/".$this->file_name))){
								
								//copy file to targetlocation
								$name= $this->file_name;
								
										$count=1;
									
										while(file_exists(realpath($target_path.$_SESSION['path_sep'].$name))){
											//file already exists
											$name=$count."_".strtoupper(str_replace(" ","_",str_replace("'","",$this->file_name)));
											$count++;
										}
								
								
									copy(realpath("temp/".$this->file_name),realpath($target_path).$_SESSION['path_sep'].$name);
									
								unlink(realpath("temp/".$this->file_name));
								$this->file_name=$name;
							
							}
						}
					
					
					}
		//update queries

			SqlQuery("","update single_images set  file_name='".$this->file_name."', size='".$this->size."', name='".$this->imagename."' where uuid ='".$this->uuid."';");
			
			//SqlQuery("","delete from parent_pdf_xref where")
			//SqlQuery("","insert into parent_pdf_xref set parent_uuid='".$parent_uuid."', pdf_uuid='".$this->uuid."' ");
		
		}
	}
	
	function DeleteFile(){
	//this function will delete the specific file assocatated with the pdf file object.
			if($this->file_name != ""){
				if(file_exists(realpath($this->file_path.$this->file_name))){
					unlink(realpath($this->file_path.$this->file_name));
					$this->file_path="";
					$this->file_name="";
					$this->imagename="";
				}
		
		
			}
		
	
	
	
	}

	function DisplayInput($formname,$control,$name="Single"){
	//this function will display the inputs for a pdf file
	echo"<script language=\"javascript\" type=\"text/javascript\">
			function validate_format".$this->inputname."(){
				if(document.".$formname.".imagefile".$this->inputname.".value !=''){
					var stringlength=document.".$formname.".imagefile".$this->inputname.".value.length;
					var extension_name=document.".$formname.".imagefile".$this->inputname.".value.substring(stringlength-3,stringlength);
					if(extension_name != 'jpg' &&  extension_name != 'gif' ){
						window.alert('Please make sure you are uploading a .jpg  or .gif file with those extensions only.');
					}else{
						document.".$formname.".control.value='".$control."';
						document.".$formname.".submit();
					}
				}else{
					window.alert('Please choose and upload an image file.');
				}
			}
		</script>";
	
		
		echo "<tr>
				<td align=\"right\" class=\"required\" valign=\"top\" style=\"padding-top:6px;\">".$name." Image (.jpg only):</td>
				<td><input name=\"imagefile".$this->inputname."\" type=\"file\" size=\"35\" >";
				DisplayButton("upload image","javascript:validate_format".$this->inputname."()");
		echo "	</td>
			</tr>";
		echo "<tr>
				<td class=\"not\" align=\"right\">Current File: </td>
				<td><input name=\"imagename".$this->inputname."\" type=\"text\" size=\"40\" value=".chr(34).$this->imagename.chr(34)."></td>
			</tr>";
		$path=$this->file_path.$this->file_name;
		
			
				
		if($this->file_name != ""){
			echo "<tr><td align=\"right\" class=\"not\">Link to Current Image: </td><td><A href=\"".$path."\" target=\"_new\" class=\"subnav\" >Click Here to View</a></td></tr>";
		}
	}

	function SaveFromOptionValue(){
	
	
	
	}
	function UpdateValues(){
	//this function will upload the file to the server temp directory
	
		if(isset($_POST["imagename".$this->inputname])){
			$this->imagename=$_POST["imagename".$this->inputname];
		
		}
		if(isset($_FILES["imagefile".$this->inputname])){
			//file value isset so deal with file upload
					$temp_dir = realpath("temp");
					//print_r($_FILES["imagefile"]);
					//upload pic to temp directory
					if(isset($_FILES["imagefile".$this->inputname])){
					
					$name=strtoupper(str_replace(" ","_",str_replace("'","",$_FILES['imagefile'.$this->inputname]['name'])));
						$count=1;
						
							while(file_exists(realpath($temp_dir.$_SESSION['path_sep'].$name))){
								//file already exists
								$name=$count."_".strtoupper(str_replace(" ","_",str_replace("'","",$_FILES['imagefile'.$this->inputname]['name'])));
								$count++;
							}
					
							$uploadtarget=$temp_dir.$_SESSION['path_sep'].$name;
				
				
				
				//file data exists
					if(move_uploaded_file($_FILES['imagefile'.$this->inputname]['tmp_name'], $uploadtarget)){
					//success
					
					$oldfilepath=$this->file_path;
					$this->file_path = "temp/";
					
					$temp = explode(".",$name);
					$this->imagename= $temp[0];
					$oldfilename= $this->file_name;
					$this->file_name= $name;
					$this->size=$_FILES['imagefile'.$this->inputname]['size']/1000;
					//echo"<br>bbk".$this->pdfname;
					
					//delete old file if it exitsed
					if($this->file_name != "" && $oldfilename != "" && $oldfilename != $this->file_name){
					//the file has changed so 
					$this->filehaschanged=1;
					//delete the old file
						if(file_exists(realpath($oldfilepath.$oldfilename)) && $oldfilename != ""){
								unlink(realpath($oldfilepath.$oldfilename));
						
						}
					
					}
					
					}else{
					echo "no upload";
					}
	
	}

		
		
		
		}


	}
}
?>

Open in new window


What you're saying is that there is a flaw in the way the data is being generated. My question is: Do you see anything in the SingleImage class that even produces a featured_image_index_1 variable? I hear you saying that there's some data present, but I can't figure out where it would be coming from.
0
 
LVL 33

Assisted Solution

by:Slick812
Slick812 earned 125 total points
ID: 38794874
greetings,
I am reluctant to post here to help you due to your presented code scramble in EE question of -
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_27996781.html

, but will try anyway ? ?
First the  featured_image_index_1 in your code presentation of this question has absolutely nothing to do with class SingleImage ,
please look at your code for class Product where in it's  "var"  definitions you have "featured_image_index_1"
and look at where $this->featured_image_index_1  is initialized with some code line like -
$this->featured_image_index_1 = new SingleImage;
or other code working
0
 
LVL 34

Assisted Solution

by:gr8gonzo
gr8gonzo earned 250 total points
ID: 38794920
I'm saying that when you do something like this:

$variable = "Hello world " . $something;

...then PHP will see that you're concatenating $something, so it wants to treat it like a string. However, if $something is an object, then you'll get that error.

Now, WHERE that actually manifests itself is the next question. I would probably suggest looking for a typo in your code, where you WANTED to type this:

$this->variable

but typed:

$this-variable

instead, leaving out the > character. That would also cause PHP to try to convert "$this" into a string. It doesn't have to be $this, either. It could be any object instance:

$x = new ObjectOfSomeKind();
echo "Hello " . $x-something;
0
 

Author Comment

by:brucegust
ID: 38794964
under class Product, there are two references to featured_image_index_1, and in both instances it's $this->featured_image_index_1=new SingleImage("featured_image_index_1");

So, it would appear as though the SingleImage class is involved somehow, but I can't tell...
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 108

Accepted Solution

by:
Ray Paseur earned 125 total points
ID: 38795170
Perhaps you can extend the SingleImage class to provide a method of the name __toString() so you can render the object the way you want it to read in a string variable.
0
 

Author Comment

by:brucegust
ID: 38795407
Guys, I've made a command decision...

It is a concession, but since this isn't my code, it's an antiquated infrastructure and the error doesn't effect anything material from the user's standpoint, I've decided to simply eliminate the error by commenting it out and documenting what I've done should anyone come after me and want to know what's going on.

After several hours trying to untangle this mess, fixing some problems and discovering others, I'm opting for a practical resolution at this point and we'll pick the baton up again should something more significant raise it's ugly head.

Thanks for your time and amen...
0
 
LVL 33

Expert Comment

by:Slick812
ID: 38795490
@brucegust,  you are missing the point of the Object Oriented code work you have in the Product Class, It some how is responsible for for keeping tract of several Images,  To have a data holder for each image it uses a Sub-Object as a SingleImage Class Object, Each SingleImage Object creates and uses a Unique ID which is labled as uuid in the var of the SinsleImage Class, , some how in your DELETE database SQL writen as
DELETE FROM single_images
WHERE  uuid='".$this-> featured_image_index_1."'
OR uuid='".$this-> featured_image_index_2."'
OR uuid='".$this->diagram_thumb."'
OR uuid='".$this->diagram_large."'
");

someone added the $this->featured_image_index_2 and the $this->featured_image_index_2 and the $this->diagram_thumb and the $this->diagram_large without knowing what they were doing, and did NOT use them as Objects but as Strings, It is my view you do not need to Change the SingleImage  but merely to use the proper property, all of the delete's ask for an equal to uuid as -
OR uuid="
and all of these have a property called uuid, it can not be unmeaningful coincidence that the SingleImage has a uuid listed that IDENTIFIES ONE image in the data base. if this means to extract (delete) all image references (ID) for One Product's many Images from the Table, then you would do it by taking out it's unique ID to the main image, the featurtured images, the thumbnail image and the large Diagram Image. . .
This will get you the SingleImage uuid -
$this->featured_image_index_1->uuid


code to consider
DELETE FROM single_images
WHERE  uuid='".$this->featured_image_index_1->uuid."'
OR uuid='".$this->featured_image_index_2->uuid."'
OR uuid='".$this->diagram_thumb->uuid."'
OR uuid='".$this->diagram_large->uuid."'
");
0
 

Author Comment

by:brucegust
ID: 38796661
Slick! I used your code and the error went away. Because I value the opportunity to learn about what's going on and not simply copy and paste, I want to try and explain back to you what it is that you did and why it worked.

The error that I was getting was not being generated because of an absence of data. Rather, it was the wrong kind of data. In other words, in order for the delete function to work, it needed a string - in this instance, the uuid - and the original code ($this->featured_image) was not producing that.

From what I've been able to gather thus far, an object is something a class produces using functions and variables. Within a class, a variable is referred to as an object and a function is referred to as a method.

The delete query in its original state stopped short of referencing a property (a string), rather it referenced the name of a column within the single_images table as opposed to the data within that column.

Your solution worked because you changed the code so it was looking for and retrieving the uuid within the various column names.

Is that correct?

BTW: Thank you very much for not just "fixing it," but helping me grow as a programmer.
0
 
LVL 33

Expert Comment

by:Slick812
ID: 38796785
Well, I read your "I used your code and the error went away" post, and there are some speaking about Object Oriented code that I will do first,
You say = "Within a class, a variable is referred to as an object and a function is referred to as a method."
a YES to the "a function is referred to as a method"
a NO to the "a variable is referred to as an object"  a variable in the public or (in your code) the var definition is called a Property , a property can be an integer, a string, an array, AND can be an object.
An Object is a Coding "creation" that does NOT exist until the PHP new word is used, as -
$obj = new container("object holds my information as a group-together as in a container");

you say = "an object is something a class produces using functions and variables", , this is sort of kinda of maybe correct,
But the Class is a written code Definition that tell PHP what to do (function-method) and what to "Save" into the container (object group-together) as a $this->variable, which does not disappear after the method is used, and can be accessed-changed again and again from the code Object variable $obj->uuid  AND in the Class definition as $this->uuid, This is an advantage to using OO, . . in that you can make several different Objects from one class (like SingleImage Class in your case), and have different uuid in each one, and this uuid does NOT get mixed up or confused (to PHP) even though it has the same identifier uuid
echo $obj1->uuid; // outputs 'a7b2fc62da'
echo $ob22->uuid; // outputs 'bcda67e6ff'

You say = "The delete query in its original state stopped short of referencing a property (a string), rather it referenced the name of a column within the single_images table as opposed to the data within that column. "

a YES to "The delete query in its original state stopped short of referencing a property (a string)"
a NO to = "it referenced the name of a column within the single_images table as opposed to the data within that column. "
to Me It referenced an Object as $this->featured_image_index_1
but the
OR uuid='
referenced a column uuid within the single_images table


That column name is NOT "featured_image_index_1", nor is the "data within that column" a PHP object,
just so you know, you can not place an Object into a Database, and get an Object out of the database later, nor can you "store" a code created object in to file, and just read the file and it returns a fully functional PHP object.
It is possible to "store" an object as a "String" and then get the string later out of storage, and then code create a similar object with that string, but it is NEVER the same object as start, but can be identical in all of this properties for using it.

Object variables rarely will work as a String value, but they can be made use as a string if defined to do that, as ray said with  __toString()  , but this is generally used to save code writting, if the majority of times the Object variable is used to get a single value, a programming "Shortcut" as
echo $reports->LastQuarterMonthlyOutput('euros');// called 20 times in code
turns into
echo $reports; // 20 less code writing work
but I have not seen it all that much, and can have other reasons to use as well
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Router for PHP reqeusts 12 33
php image upload 3 27
Page showing diff display 4 22
Apostophes in PHP generated form 6 20
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to count occurrences of each item in an array.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now