开发者

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?

开发者_JAVA百科Or, is there a way to call a class and not have it execute the function with the same name?


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.


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.


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.


$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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜