2

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?

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

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.

2 Comments

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

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.

2 Comments

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.
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.
0

$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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.