Log in

View Full Version : function return



city_coder
07-04-2010, 05:02 PM
hi guys is it possible to do something like this??



class A {
private $test;
private $anotherTest;

function getTest() {
return $this->test;
}

function setTest($value = '') {
$this->test = value;
}

function getAnotherTest() {
return $this->anotherTest;
}

function setAnotherTest($value = '') {
$this->anotherTest = value;
}
}

class B {
private $variable;

function getVariable() {
return $this->$variable;
}

function setVariable($value = '') {
if($value != '') {
$a = new A();
$a->setAnotherTest($value);

$return $a;
} else {
//do something else
}
}




$b = B::setVariable('text');
echo $b->getAnotherTest();


essentially i want to know whether i can pass a class in a return statement or you really just cant & it has to be as an array?

cheers in advance guys.

djr33
07-05-2010, 01:04 AM
I'm not sure I understand exactly what you are trying to accomplish. Can you make a simpler example? There's a lot going on there that makes this confusing.
You should be able to return any variable regardless of its contents. Returning a variable just creates a copy of that variable in the other context... there should be no real problems.

The only thing that jumps out at me in your code is that you have a type: $return instead of return. "$return" is a variable named return, not a command.

traq
07-05-2010, 02:31 AM
one other thing:
you are trying to call B::setVariable(), but it's not a static method. Choose one of two solutions:

<?php
$b = new B();
$b->setVariable();
?>or
<?php
class B{
// ...
static function setVariable(){
// ...
}
// ...
}
?>
try that and see where it takes you. To answer your question ("can you return a class (actually, the object the class created)"), yes, but beyond being kinda interesting, I've rarely found it to be useful.

djr33
07-05-2010, 04:02 AM
Also, since there are clearly some errors in this script, seeing those will help us. If you see no errors (blank screen?) then this means you need to turn on error reporting so you can diagnose the problems. There is information available by search for "php error reporting" and on php.net for the function error_reporting().

djr33
07-05-2010, 04:25 AM
Also, since there are clearly some errors in this script, seeing those will help us. If you see no errors (blank screen?) then this means you need to turn on error reporting so you can diagnose the problems. There is information available by search for "php error reporting" and on php.net for the function error_reporting().

city_coder
07-05-2010, 08:05 AM
Sorry for the confusing example guys....il make it more simple i promise :P

heres the scenario, i send a function in a class a parameter. The function then connects to the database (which as you probably noticed was my other thread about a database class, but thats besides the point) & returns a row from the table based on the data. So hopefully this is easier to understand....

(btw, this is not my code im using exactly, this is a cut down version)


class Customer {

var $name;
var $email;

function getEmail () {
return $this->email;
}

function setEmail ($value = '') {
$this->email = $value;
}

//etc etc for getting & setting

function readCustomer ($value = '') {
//$value will be an email address
$sql = "SELECT * FROM customer WHERE email = '$value'";
$result = mysql_query();
$customer = new Customer();
if(//results greater than 0) {

$customer->setEmail = //row from table
$customer->setName = //row from table

} else {
$customer->setEmail = null;
$customer->setName = null;
}

return $customer;
}

}


then to access it....



$customer = new $customer::read('test@test.com');
echo $customer->getEmail();
echo $customer->getName();


The only reason i wanted to return a different type of object was cos i want to return the data in an object & a response message that i would then use to check whether any results came back & i could set error flags & messages etc.

I hope that explains things a little better.

Cheers guys

traq
07-05-2010, 05:49 PM
again, yes, you can return an object. However, if you only need the data/messages/etc., it would be much simpler and more efficient to use an array. There's no reason to return an object unless you actually need to manipulate the object (e.g., you're going to use the object's functions) after it's returned.

also, your sample code above will still not work. If you want to use an object's methods outside the object (e.g., from your regular script), you need to declare them as static methods in the class definition. Otherwise, you won't be able to use them from the outside: you'll have to create a new object from the class and use that to access the methods.

(BTW, based on the way your code is written in your example, this:
$customer = new $customer::read('test@test.com');
should be something like this:
$customer = new customer();
$customer->readCustomer('test@test.com');
)

If this is one of your first attempts at using object-oriented programming, I'd suggest doing something much simpler to start. Find some tutorials you can understand and do lots of experimenting. It took me quite a while to figure out OOP; and it doesn't work quite the way you might expect it to.



This is not correctly formed, either:

<?php
// ...
if(//results greater than 0) {

$customer->setEmail = //row from table
$customer->setName = //row from table

} else {
$customer->setEmail = null;
$customer->setName = null;
}
// ...
?>$customer->setEmail (et.al.) are not variables; they're methods. You can't set them the way you set variables.
try something like:
<?php

if( /* $results = results from DB*/ ){
$customer->setEmail($results['email']);
$customer->setName($results['name']);
}else{
// you don't have to "set" the values as null; they're already empty to start.
// setting another property might be more helpful:
$customer->setFoundCustomer(FALSE);
// or even:
// return FALSE;
// instead of returning the customer object
}

?>

city_coder
07-05-2010, 06:48 PM
OK, so its not my first attempt at using OOP. Iv been doing it in java for 3 months in SAP so I know how it works there. Iv just wanted to do this project in PHP because I know it better than moving to JSP & learning that more.

So you said it is possible to return an object but you didnt say how, which is what my question was.

Also you didnt give any examples of how that code was structured in the class & what was set.

If you can give me some examples please? That would be a great help!

Cheers.

traq
07-05-2010, 07:05 PM
well, PHP is still different than Java. if you're already familiar with OOP, then you're ahead of the game; perhaps this (http://www.php.net/manual/en/language.oop5.php) would be helpful with sorting out php-specific syntax and constructs.

about examples: sorry - I thought you were just asking if what you had would work and how it would work. Aside from the typos and preceding syntax issues, the "return" part of your code was fine. An object is returned the same way anything else is:

<?php

function return_object(){
$object = new myClass();
return $object;
}

?>
To declare an object as static (so you can access it like $var = myClass::static_method(); ), just put the static keyword in front of it in the class definition:
<?php

myClass{

static function static_method($var){
// do stuff
}

}

?>

city_coder
07-08-2010, 12:21 PM
Sorry its taken so long to reply...

Cheers for the response. So just to double check this now, if i do...



class Customer {
private $fName;
private $lName;
private $errorOccurred;
private $errorText;

function setLName($value = '') {
$this->lName = $value;
}

function

function readCustomer ($email = '') {
$sql ="SELECT * FROM customer WHERE email = '$email'";
$customer = new Customer();
if result then {
$customer->setLName($result['lName']);
//etc
} else {
//set flag same as setting lName
}

return $customer;
}
}


then to read it



$customer = new Customer();
$customer->readCustomer('test@test.com');

if($customer->getErrorOccurred()) {
//error couldnt get user details from db
} else {
//great, get other customer details
echo $customer->getLName();
}



right? or wrong?

also could i do this?



$customer->Customer::readCustomer('test@test.com');


or does that mean im doing things differently?

cheers for the help guys, i know im being stupid.

djr33
07-08-2010, 08:51 PM
Responding to the last example, that doesn't make much sense:

Classname::function(.......);
That's the syntax for calling a static function from a class without an object.

$variable::function(....);
That's what you are doing above (even though it's a little more complex), and I don't see any reason this would ever be needed, and it doesn't really make sense: I'm almost positive this would give an error.

Let's say you have $x that you want to run through Class Z's function Y:
Z::Y($x);

Does that make sense?

Or, you can create an object $o of that class:
$o = new Z;
$o->Y($x);

You can also layer classes (but it can become confusing):
$p = new W;
$p->o = $o;
$p->o->Y($x);

But you never would use a class and a static function like above.

Maybe you want to do:
ClassName::function($obj->subobj);
...does that help?

That is calling a static method on the variable "subobj" (subobject) of class $obj.

Here's another example. I believe these two are equivalent:

$x = new MyClass;

//version 1:
MyClass:MyFunc($x->y);

//version 2:
$x->MyFunc($x->y);

//Or, you can refer to $this->y within the definition for MyFunc....

I hope that makes a little more sense...

traq
07-08-2010, 09:12 PM
city coder, I don't think you have a clear understanding of what "static" means in our conversation above.

Your function readCustomer() is not a static function. You will never be able to access it with the syntax Customer::readCustomer().

In php5, there are four types of methods (functions within a class)(these actually apply to class variables (properties) as well):
1. public. A "public" function can be accessed by code from outside the class (e.g., from you regular php scripts) after you have created an object from the class. The syntax is like this: $object = new class();, then $object->public_method();. "Public" is the default method type. If you don't declare otherwise (as you are not), then your method will be "public."

2. protected. Protected methods can be used only by the class itself, and by any class that extend it. This means that the method can be used by your classes, but can't be accessed or triggered directly by any outside code. So, $class->protected_method(); will work if it is a line of code inside the class (or in a class that extends the class), but if you write it in your regular script, it won't.

3. private. Private methods are like protected methods, except they can only be accessed by their own class (classes that extend the method's class have no access, nor does any outside code).

4. static. A static method can be accessed from anywhere, even if there is no related object. This is the type that uses the syntax class::static_method();. Static methods are usually utility functions, or other things that you might do frequently but don't need the support of the entire class.
They also have no access to the rest of the class (except other static methods, of course) because they aren't working from "inside" the object, even if the object exists. So a static method could not be accessed like this: $object = new class(); $object->static_method();, nor can they access other class functions by using $this->some_non-static_method();. Really, it might as well be a single function written outside the class, but it is a good way to keep related functions organized.

The rest of it looks functional enough (conceptually; once you finish writing it, of course), but I do have a suggestion.

It seems that (in this example) you want to use the readCustomer method to "start up" your class. If so, there is a method you could be using called __construct() (two underscores). The __construct method, if present, is run automatically (or, as php.net says, "automagically") when an object is created. So, if you write it like this:
<?php

class Customer {
private $fName;
private $lName;
private $errorOccurred;
private $errorText;

function __construct($email = '') {
// set your SQL statement
// if there are results
// use class methods to assign the values to the class variables
// otherwise, return error message
}
}

?>then simply calling $customer = new Customer('test@test.com'); will return an object with all the information you're looking for.

What's even better (IMHO) is to use the __construct() method to define the logic you want to use to create your object (instructions) rather than actually doing everything. So:
<?php

class Customer{
private $name;
private $email;
private $whatever;
private $errorMessage;
private $queryResults;

// __construct() must always be "public" !!!
public function __construct($email){
if($this->findCustomerByEmail($email)){
$this->email = $email;
$this->setCustomerName();
$this->setCustomerWhatever();
}else{
$this->setErrorMessage();
}
}

private function findCustomerByEmail($email){
// use email to search DB and return customer row (if any)
// blahblahblah
$this->queryResults = $results;
}

private function setCustomerName(){
// use $this->queryResults to set name
// maybe something like $this->name = $this->queryResults['name'];
}

private function setCustomerWhatever(){
// etc.
}

private function setErrorMessage(){
// set error message
if($error){ return $this->errorMessage; }
}

}

?>