Dylan
Dylan

Reputation: 859

Calling PHP Class

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?

Upvotes: 2

Views: 17012

Answers (4)

mauris
mauris

Reputation: 43619

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.

Upvotes: 2

txyoji
txyoji

Reputation: 6848

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.

Upvotes: 2

Galen
Galen

Reputation: 30170

$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

Upvotes: 0

Matt Huggins
Matt Huggins

Reputation: 83269

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.

Upvotes: 0

Related Questions