Tycoon Talk
Become a Big fish!
The number 1 forum for online business!
Post topics, ask questions, share your knowledge.
Tycoon Talk is part of Freelancer.com - find skilled workers online at a fraction of the cost.

PHP Forum


You are currently viewing our PHP Forum as a guest. Please register to participate.
Login



Freelance Jobs

Reply
Getting variables out of functions?
Old 07-02-2008, 06:03 AM Getting variables out of functions?
pealo86's Avatar
Super Spam Talker

Posts: 876
Name: Matt Pealing
Location: England, north west
Trades: 0
I know that internal variables are destroyed from functions when theyve finished executing, but is there no way to obtain there value somehow?

There are two variables in a function I have created that I could really do with accessing!
__________________

Please login or register to view this content. Registration is FREE
pealo86 is offline
Reply With Quote
View Public Profile Visit pealo86's homepage!
 
 
Register now for full access!
Old 07-02-2008, 06:19 AM Re: Getting variables out of functions?
tripy's Avatar
Do not try this at home!

Posts: 3,621
Name: Thierry
Location: I'm the uber Spaminator !
Trades: 0
return them in an array:
PHP Code:
$glob1="this is global1";
function 
fx(){
  
$priv1="this is private 1";
  
$priv2="this is private Ryan";
  return array(
$priv1,$priv2);
}
$aryRet=fx();
print_r($aryRet);
/*
should display:
array
  [0] => "this is private 1"
  [1] => "this is private Ryan"
*/ 
__________________
Only a biker knows why a dog sticks his head out the window.
tripy is offline
Reply With Quote
View Public Profile Visit tripy's homepage!
 
Old 07-02-2008, 08:30 AM Re: Getting variables out of functions?
Skilled Talker

Posts: 94
Trades: 0
I prefer to do it this way :/


function fx(){
$priv[1]="this is private 1";
$priv[2]="this is private Ryan";
return $priv;
}
$aryRet=fx();
print_r($aryRet);
/*
should display:
array
[0] => "this is private 1"
[1] => "this is private Ryan"
*/
__________________
Sell Templates? Try our
Please login or register to view this content. Registration is FREE
! See a live
Please login or register to view this content. Registration is FREE
ChadR is offline
Reply With Quote
View Public Profile
 
Old 07-02-2008, 10:26 AM Re: Getting variables out of functions?
tripy's Avatar
Do not try this at home!

Posts: 3,621
Name: Thierry
Location: I'm the uber Spaminator !
Trades: 0
As a matter of taste, passing the variable by reference would even be cleaner:
PHP Code:
$var1="I'm outside of your function";
$var2="looking at your tubes";

function 
fx($work1$work2){
  
$work1="I'm in your function";
  
$work2="looking at your pipes";
}


fx(&$var1,&$var2);

echo 
$var1//=>I'm in your function
echo $var2//=>looking at your pipes 
With a traditional function($variable), you pass a copy of $variable to the function, and you return again a copy of the function's local scope variable.

With function(&$variable), you give a reference to the memory emplacement where the content of the variable is stored, thus making any changes in it ignore the scope limitations and avoiding the need to return anything.
__________________
Only a biker knows why a dog sticks his head out the window.
tripy is offline
Reply With Quote
View Public Profile Visit tripy's homepage!
 
Old 07-02-2008, 11:09 AM Re: Getting variables out of functions?
coldwind's Avatar
Novice Talker

Posts: 12
Name: Konstantin Leboev
Trades: 0
Quote:
Originally Posted by tripy View Post
As a matter of taste, passing the variable by reference would even be cleaner:
PHP Code:
$var1="I'm outside of your function";
$var2="looking at your tubes";

function 
fx($work1$work2){
  
$work1="I'm in your function";
  
$work2="looking at your pipes";
}


fx(&$var1,&$var2);

echo 
$var1//=>I'm in your function
echo $var2//=>looking at your pipes 
With a traditional function($variable), you pass a copy of $variable to the function, and you return again a copy of the function's local scope variable.

With function(&$variable), you give a reference to the memory emplacement where the content of the variable is stored, thus making any changes in it ignore the scope limitations and avoiding the need to return anything.
I disagree with you. First of all it's deprecated (http://ru2.php.net/manual/en/functions.arguments.php, "As of PHP 5, Call-time pass-by-reference has been deprecated").

You may use that code:
PHP Code:
function fx (&$work1, &$work2) {
    
$work1 "I'm in your function";
    
$work2 "looking at your pipes";
}

fx($var1$var2); 
But I prefer to use list construction:
PHP Code:
function some_function () {
    
$var1 'variable 1';
    
$var2 'variable 2';

    
// some code goes here ...

    
return array($var1$var2);
}

list (
$my_var1$my_var2) = some_function();
echo 
$my_var1 ' and ' $my_var2
coldwind is offline
Reply With Quote
View Public Profile
 
Old 07-02-2008, 11:32 AM Re: Getting variables out of functions?
tripy's Avatar
Do not try this at home!

Posts: 3,621
Name: Thierry
Location: I'm the uber Spaminator !
Trades: 0
Quote:
First of all it's deprecated
Hmm, I didn't knew that...
What I knew is that it's the default behaviour in PHP5, when parameter copy was in PHP4.

I have to admit I don't have used the pass by reference method for several years.
Working with object somewhat free yourself from that
PHP Code:
function fx(){
  
  
$ret =new stdClass();
  
$ret->val1="this is";
  
$ret->val2="funky!";
  return 
$ret
}

$obj=fx();
echo 
$obj->val1;  // => this is
echo $obj->val2;  // => funky! 
So, let just say that there are many ways of returning several variable from 1 function.

PS: I decided that I will have the last word in that thread. And I am perseverant :-)
__________________
Only a biker knows why a dog sticks his head out the window.

Last edited by tripy; 07-02-2008 at 11:33 AM..
tripy is offline
Reply With Quote
View Public Profile Visit tripy's homepage!
 
Old 07-02-2008, 11:41 AM Re: Getting variables out of functions?
coldwind's Avatar
Novice Talker

Posts: 12
Name: Konstantin Leboev
Trades: 0
Well, further discussion in OOP will lead to using incapsulation and private properties. So if you use classes do use private $val1 and $val2 and access them by functions:
PHP Code:
$obj->getVal1();
$obj->getVal2(); 
Of course, you may use magic methods such as __get for transparently access them... but better way is functions, IMHO
coldwind is offline
Reply With Quote
View Public Profile
 
Old 07-02-2008, 01:37 PM Re: Getting variables out of functions?
Learning Newbie's Avatar
Defies a Status

Latest Blog Post:
Astounding Republican Paranoia
Posts: 5,662
Name: John Alexander
Trades: 0
Quote:
Originally Posted by KkillgasmM View Post
I know that internal variables are destroyed from functions when theyve finished executing, but is there no way to obtain there value somehow?
Variables fall out of scope, and are freed, much like biological death.

You have several ways of getting information values out of a function. Return values are the obvious one. So are output parameters, or even just passing in pointers to memory locations that can be edited. Most people would say both of these aren't "clean".

Return an array, but that's not very clean, either. That creates a strong coupling between function and consumer, because now you need to know fn[2] is such and such, while fn[3] is something else. You might even need to know the data types! This will work, but it's not such a good idea. A customized collection would be better - key value pairs at least give you some insight into what each item is.

Or, a much cleaner (but more overhead) way to accomplish this is to return an XML document, which lets you return as much data in any structure as you'd like.
__________________

Please login or register to view this content. Registration is FREE


Please login or register to view this content. Registration is FREE
Learning Newbie is offline
Reply With Quote
View Public Profile
 
Old 07-02-2008, 06:15 PM Re: Getting variables out of functions?
mgraphic's Avatar
Truth Seeker

Latest Blog Post:
JAMISONTUNES
Posts: 2,918
Name: Keith Marshall
Location: Connecticut
Trades: 0
Quote:
Originally Posted by coldwind View Post
I disagree with you. First of all it's deprecated (http://ru2.php.net/manual/en/functions.arguments.php, "As of PHP 5, Call-time pass-by-reference has been deprecated").
I don't see that anywhere
__________________

<mgraphic /> - I don't have a solution but I admire the problem.
mgraphic is offline
Reply With Quote
View Public Profile
 
Old 07-02-2008, 06:24 PM Re: Getting variables out of functions?
tripy's Avatar
Do not try this at home!

Posts: 3,621
Name: Thierry
Location: I'm the uber Spaminator !
Trades: 0
it's below the manual, in the user comments....

Beside, another method just stroke me.
You could create the variables directly into the global scope:
PHP Code:
function fx(){
  
$GLOBALS['var1']="this is";
  
$GLOBALS['var2']="groovy";
}
fx();
echo 
$GLOBALS['var1'];
echo 
$GLOBALS['var2']; 
__________________
Only a biker knows why a dog sticks his head out the window.
tripy is offline
Reply With Quote
View Public Profile Visit tripy's homepage!
 
Old 07-02-2008, 09:00 PM Re: Getting variables out of functions?
mgraphic's Avatar
Truth Seeker

Latest Blog Post:
JAMISONTUNES
Posts: 2,918
Name: Keith Marshall
Location: Connecticut
Trades: 0
The call time to reference is depreciated (so it seems), but you can still declare function arguments by reference.
__________________

<mgraphic /> - I don't have a solution but I admire the problem.
mgraphic is offline
Reply With Quote
View Public Profile
 
Old 07-03-2008, 05:08 AM Re: Getting variables out of functions?
coldwind's Avatar
Novice Talker

Posts: 12
Name: Konstantin Leboev
Trades: 0
Quote:
Originally Posted by mgraphic View Post
The call time to reference is depreciated (so it seems), but you can still declare function arguments by reference.
As I said before (may be no so clearly):
PHP Code:
// Deprecated function call
function fx ($work1$work2) {}
fx(&$var1, &$var2);

// Allowed function call
function fx (&$work1, &$work2) {}
fx($var1$var2); 
Quote:
Originally Posted by tripy View Post
Beside, another method just stroke me.
You could create the variables directly into the global scope
Oh man, that's horrible method... to use global variables... brr... where did you see that?
__________________
P.S. Sorry for my bad English... +)
P.P.S. If you can't understand my English feel free to ask some questions or correct me.
coldwind is offline
Reply With Quote
View Public Profile
 
Old 07-03-2008, 06:26 AM Re: Getting variables out of functions?
tripy's Avatar
Do not try this at home!

Posts: 3,621
Name: Thierry
Location: I'm the uber Spaminator !
Trades: 0
Quote:
Oh man, that's horrible method... to use global variables... brr... where did you see that?
I use it all the time.
Rather than doing global('myObject') in each procedure where I want to access my db wraper, I directly put the wrapper in the global scope, and adress it always that way.
PHP Code:
//into my class initilisation:
$GLOBALS['objDb']=new clDb();

//and into a method of my "users" class:
/**
 * Try to log a user in
 * @param Array $ary The array with pwd/email
 * @return Boolean|Int   Return FALSE if the login was not successful. The userId is returned in case of success
 */
protected function login($ary){
  
$email=sanitize($ary['inpTxtEmail']);
  
$pwd=sanitize($ary['inpPwdPass']);
  
$sql=<<<SQL

select userlogin('
$email','$pwd')

SQL;
  
$res=$GLOBALS['objDb']->doQuery($sql);
  while(
$o=$GLOBALS['objDb']->fo($res)){
    if(
$o->userlogin=='BAD_PASSWORD'){
      return 
false;
    }
    elseif(
$o->userlogin=='NO_EMAIL'){
      return 
false;
    }
    else{
      
$GLOBALS['objTrans']->__construct();
      return 
$o->userlogin;
    }
  }
  return 
false;

And why is this so horrible ? I don't say ysou should use it for everything, but it's handy for some cases.
__________________
Only a biker knows why a dog sticks his head out the window.
tripy is offline
Reply With Quote
View Public Profile Visit tripy's homepage!
 
Old 07-03-2008, 07:09 AM Re: Getting variables out of functions?
coldwind's Avatar
Novice Talker

Posts: 12
Name: Konstantin Leboev
Trades: 0
Using global variables is not the best idea. I don't say "hey, don't use it! and if you do, rewrite it!", but it's some sort of code smell.

When you use few global variables in a simple personal project it could be ok, but still dangerous. It's become too difficult to debug such code when the project starts to grow. For example, your project uses one global variable $objDb and you decides to use some cool library, but it uses own global variable $objDb and it's not the same object. Then you have to modify your code and not to use $objDb. Again, it can be ok for your personal project... But, imagine if someone else uses your project and writing some modules/extensions for your project. That's mean that to change using global variables become more difficult or even impossible. Be couse you using global variables all over the project.

Again, for small personal projects it may be ok to use global variables with one instance, but, imho, you'd better to use singleton pattern.

As for me I had to change of using global variable $db all over big project (internal ERP system for project managing) when I started to use PHPUnit (I needed to use it, but it couldn't run with database object in the global variable). So I created simple class to hold database object and used it.

Another example is that when you use global variables it's hard to change it to something better. Entire project knows that global variable $somevar is an array (for example) and it can be changed by any function and you would spend a lot of time to figure out which one changed it.

p.s. hope, there was not so many mistakes in my sentences to make them misunderstandable.
__________________
P.S. Sorry for my bad English... +)
P.P.S. If you can't understand my English feel free to ask some questions or correct me.
coldwind is offline
Reply With Quote
View Public Profile
 
Old 07-03-2008, 07:22 AM Re: Getting variables out of functions?
coldwind's Avatar
Novice Talker

Posts: 12
Name: Konstantin Leboev
Trades: 0
As for using global variable DB it depends on the project. Sometimes it's better to use static class, sometimes to use an object or abstract factory with singleton patterns, and may be sometimes global variable. I guess so. Anyway before using any global variable stop and think of trying to use another variant.
__________________
P.S. Sorry for my bad English... +)
P.P.S. If you can't understand my English feel free to ask some questions or correct me.
coldwind is offline
Reply With Quote
View Public Profile
 
Old 07-03-2008, 07:32 AM Re: Getting variables out of functions?
tripy's Avatar
Do not try this at home!

Posts: 3,621
Name: Thierry
Location: I'm the uber Spaminator !
Trades: 0
Quote:
For example, your project uses one global variable $objDb and you decides to use some cool library, but it uses own global variable $objDb and it's not the same object. Then you have to modify your code and not to use $objDb.
True...
But as I (usually) don't freelance and everything I realize is usually without external scripts, this never has been an issue.
Beside, with a little bit of perl magic, it's not a big deal to replace objDb to something else.

Quote:
Sometimes it's better to use static class,
I did it that way too, because (As far as I have understood it...) using a static class would have meant that each call to that class from different objects would have re-opened a connection, which I wanted to avoid.

Quote:
sometimes to use an object or abstract factory with singleton patterns
I do use an singleton like pattern, for objects like the user object.
In fact, the initialisation of the object lookup first to see if there is an "user" object in session, and then returns it. Or it creates a new empty one.
Not trully singleton, as it's not a static method in the class that take care of that.
I use a non-auto started session mechanism with a /libs/{module}/cl{module}.php + init.php in ecah directory, which allows me to import classes before the session_start() to cope with serialized object into the session.
The .ini file is called after the session is initialized, and it's him that's responsible for that singleton like behaviour.

Not the cleanest, I know, but worked admirably well for the last 2 years for me.
__________________
Only a biker knows why a dog sticks his head out the window.
tripy is offline
Reply With Quote
View Public Profile Visit tripy's homepage!
 
Old 07-03-2008, 08:58 AM Re: Getting variables out of functions?
coldwind's Avatar
Novice Talker

Posts: 12
Name: Konstantin Leboev
Trades: 0
Quote:
Originally Posted by tripy View Post
I did it that way too, because (As far as I have understood it...) using a static class would have meant that each call to that class from different objects would have re-opened a connection, which I wanted to avoid.
Nope, or I misunderstood you. When you call any method it will not re-open connection. First, becouse of calling mysql_connect second time with the same host/user/pass values will not open new connection (need to pass additional parameter to force opening new connection). And second, there is some example of how to (without testing, comments, just thoughts) use static for just one connection:

PHP Code:
class MyDB {
     
/**
     * @var Database some database object
     */
    
private static $db;

    
/**
     * @return Database some database object
     */
    
final protected static function getDB () {
        if (
is_null(self::$db)) {
            
self::$db = new Database();
            
self::$db->connect(...);
        }
        return 
self::$db;
    }

    
/**
     * Proxy method
     *
     * @param string $query Query string
     * @return resource
     */
    
public function query ($query) {
        return 
self::getDB()->query($query);
    }
}

// and some usage of this class
$res MyDB::query("select id, name from my_table"); 
Just a simple example of how it could be done (depends on project specific, whether or not to use "proxy" depends on project specific).

Quote:
Originally Posted by tripy View Post
I do use an singleton like pattern, for objects like the user object.
In fact, the initialisation of the object lookup first to see if there is an "user" object in session, and then returns it. Or it creates a new empty one.
Not trully singleton, as it's not a static method in the class that take care of that.
I use a non-auto started session mechanism with a /libs/{module}/cl{module}.php + init.php in ecah directory, which allows me to import classes before the session_start() to cope with serialized object into the session.
The .ini file is called after the session is initialized, and it's him that's responsible for that singleton like behaviour.

Not the cleanest, I know, but worked admirably well for the last 2 years for me.
Are all user objects stored in session or retrieved on demand? And why don't use spl_autoload? And why to store objects in a session if it is?
__________________
P.S. Sorry for my bad English... +)
P.P.S. If you can't understand my English feel free to ask some questions or correct me.
coldwind is offline
Reply With Quote
View Public Profile
 
Old 07-03-2008, 09:12 AM Re: Getting variables out of functions?
tripy's Avatar
Do not try this at home!

Posts: 3,621
Name: Thierry
Location: I'm the uber Spaminator !
Trades: 0
Quote:
First, becouse of calling mysql_connect second time with the same host/user/pass values will not open new connection
Yeah, but I don't use mysql. Hate it.
I'm using Potgresql, and I had issues with too many connections (which each eats a bit of shared memory) leading to the memory being full and no more connections was possible.
But it's true that I don't have seen them, and it was with Pgsql 7.0
And today, I use pgpool as a connection pooler, which makes a really good job...

Quote:
Are all user objects stored in session or retrieved on demand? And why don't use spl_autoload? And why to store objects in a session if it is?
a) There are only specific objects in session. User, transaction history (if needed) for example.

b) spl_autoload ? Never heard of it.
Okay, I did looked at it, but I don't like that kind of stuff, and I don't see what benefit I would have from using it.
I like to avoid every automagic as far as I can.
I prefer declaring which modules I use in a config file rather than using an autoload mechanism that will try to make it in my back, looking through several directory.
Call me a control freak, but that works for me.

c) I store the object in the session to keep it preserved from requests to requests, without the need of re-querying the DB on each re-instatiation of the object. That avoid me to reload user specific datas for each pages.
The less queries I send to the db, the better I am.

Just like I keep site configuration as define() in a separate file, rather than including them in a db.
__________________
Only a biker knows why a dog sticks his head out the window.
tripy is offline
Reply With Quote
View Public Profile Visit tripy's homepage!
 
Old 07-03-2008, 09:37 AM Re: Getting variables out of functions?
coldwind's Avatar
Novice Talker

Posts: 12
Name: Konstantin Leboev
Trades: 0
Quote:
Originally Posted by tripy View Post
b) spl_autoload ? Never heard of it.
Okay, I did looked at it, but I don't like that kind of stuff, and I don't see what benefit I would have from using it.
I like to avoid every automagic as far as I can.
I prefer declaring which modules I use in a config file rather than using an autoload mechanism that will try to make it in my back, looking through several directory.
Call me a control freak, but that works for me.
Well the point is that you don't need to require every needed file and to remember "if I need to require this file or it was included or I don't need this class requirement any more and need to delete require_once in this file?". And include only needed files/classes without problems. "Looking through several directories" is configured as you wish, it may be only one directory.

As an example, if your projects has more then 100-200 classes.

I don't say that you need this, but some times it may be useful as optional solution, but I found it useful for myself on a big project (couse it had been refactoring).

Quote:
Originally Posted by tripy View Post
c) I store the object in the session to keep it preserved from requests to requests, without the need of re-querying the DB on each re-instatiation of the object. That avoid me to reload user specific datas for each pages.
The less queries I send to the db, the better I am.
For user object, which is used by any page? I've got it. True, very useful.

Quote:
Originally Posted by tripy View Post
Just like I keep site configuration as define() in a separate file, rather than including them in a db.
I used it as constants and global variables but looking to INI files for storing configuration parameters.
__________________
P.S. Sorry for my bad English... +)
P.P.S. If you can't understand my English feel free to ask some questions or correct me.
coldwind is offline
Reply With Quote
View Public Profile
 
Old 07-03-2008, 10:12 AM Re: Getting variables out of functions?
tripy's Avatar
Do not try this at home!

Posts: 3,621
Name: Thierry
Location: I'm the uber Spaminator !
Trades: 0
Quote:
Well the point is that you don't need to require every needed file and to remember
Yeah, I see your point.
Never had more than a dozains of classes, so it never struck me as something that I would need to be automated.
Last time I remember I wanted to do that, I created an file that would inspect a given directory, including every files like cl*.php
But surelys spl_autoload() is more optimized that my while() was...
:-)
__________________
Only a biker knows why a dog sticks his head out the window.
tripy is offline
Reply With Quote
View Public Profile Visit tripy's homepage!
 
Reply     « Reply to Getting variables out of functions?

Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are Off





   
RSS Feed  Feeds: RSS   JS   XML
RSS Feed  Feeds for this forum: RSS   JS   XML



Page generated in 0.65588 seconds with 12 queries