Jump to content

[SOLVED] returning string from __construct not working .. why?


jaikar

Recommended Posts

hi there.

 

here is the code

 

<?php
class test {
	function __construct() {
		return 'hello';
	}
}
$d = new test;
echo $d;
?>

 

it prints object#1, anyhow i can understand the core concept, but what if when i have a situation where i will have to return a value in the constructor itself and how to grab that value? is there any way or i have to create a seperate method to grab the value? is it right to return values in the constructor? please advise...

Thanks in advance...

Because classes are objects, not strings. You're defining $d as an object, and the return value of a method within that object will not change that.

 

Constructors aren't designed to return values. It's just code that's executed when a function is called. Your best bet is to use a public class variable, and verify success/failure/returns with that.

 

To back it up with code

<?php
class test {

	public $out;

	public function __construct() {
		$this->out = 'hello';
	}
}
$d = new test;
echo $d->out;
?>

The constructor does not and cannot return a value. It in fact returns nothing - void

 

void __construct ( [mixed $args [, $...]] )

 

 

$d = new test(); returns the class object that is created.

 

The purpose of a constructor is to perform - "any initialization that the object may need before it is used." (quote directly from the php manual.)

  • 5 weeks later...

 

though this is a very old post i just found the solution and thought of sharing ...

 

using __toString as one of a method in a class returns string in the instantiation level itself.. but this works only in PHP 5.2. so no need to call a seperate method to get a value. hope it is usefull for someone

 

class test 
{

     function __construct() {
           $this->value = "Hello World";
     }

     function __toString() {
         return $this->value;
     }
}


echo new test; // prints  "Hello World";

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.