tags:

views:

73

answers:

4

Is there any way to call a php class (eg. $var = new className) and have var store the value returned by the className function?

Or, is there a way to call a class and not have it execute the function with the same name?

A: 

Constructors don't return values, they are used to instantiate the new object you are creating. $var will always contain a reference to the new object using the code you provided.

To be honest, from your question, it sounds like you don't understand the intention of classes.

Matt Huggins
I'm not very good at explaining what I mean. Right now I am calling the constructor just like a normal function and it would return data. But the issue is that the function then gets called twice, once when for the class, and once when i reference it. Is there any way to get around this without changing the name? I know another way I can do it, but i didn't really want to change it.
Dylan
can you show us the code?
Galen
I'm afraid its on multiple different pages, and not very easy to post here. I'll just go with my other idea. Thanks for the help.
Dylan
A: 

$var = new classname will always return an instance of classname. You can't have it return something else.

Read this... http://www.php.net/manual/en/language.oop5.php

Galen
+1  A: 

It is possible in PHP5 using magical method __toString(); to return a value from the class instance/object.

simply

class MyClass{

function __construct(){
  // constructor
}

function __toString(){
  // to String
  return 5;
}

}

$inst = new MyClass();

echo $inst; // echos 5

Constructors don't return value (in fact you can't do that). If you want to get a value from the instance of the class, use the __toString() magical method.

thephpdeveloper
So I would have to rename the function to __toString?
Dylan
constructors don't return value. If you want to get a value from the instance of the class, use the __toString() magical method
thephpdeveloper
+1  A: 

The function of the same name as the class was they way 'constructors' in php 4 worked. This function is called automatically when a new object instance is created.

In php 5, a new magic function __construct() is used instead. If your using php5 and don't include a '__construct' method, php will search for an old-style constructor method. http://www.php.net/manual/en/language.oop5.decon.php

So if you are using php5, add a '__construct' method to your class, and php will quit executing your 'method of the same name as the class' when a new object is constructed.

txyoji
Omg thank you sooooo much. Adding a blank __construct method is exactly what I needed to make this work. Your amazing!
Dylan