简体   繁体   中英

Using global string in PHP inside function more than once

So I have a class that looks something like this...

class foo{
    private $url = ""

    function createURL($contryCode){
        global $url;
        $url = 'google'
        echo $url;
        if($url == ''){exit()}
        $fullURL = "http://" . $url . $countryCode . "/";
        return $fullURL;
     }
}

In the next script I calling it like....

$address = $foo -> createURL(".us");

It will output the global as "google" and pass the check against null but when I concatenate it fills the string with null values. Aside from "global is bad" I can't find a reason for this.

Anyone have any ideas?

EDIT: A little more info... The $address is filled with " http:/// " (the http:// and / constants, but not the global).

The method implementation itself looks fine, as mentioned above in my comment. However I have the impression that you did not yet fully understand how to use that class definition of yours. Take a look at this simply example:

<?php
class foo{
    private $url = ""

    function createURL($contryCode){
        global $url;
        $url = 'google'
        echo $url;
        if($url == ''){exit()}
        $fullURL = "http://" . $url . $countryCode . "/";
        return $fullURL;
     }
}

$fooObj = new foo;
$address = $fooObj->createURL(".us");
var_dump($address);

A side note: global variables are indeed considered bad style in most situations. However that does not mean that they would not work as expected in general. There are two main issues with global variables and you certainly should avoid them: 1. it is very hard to debug and maintain software using such global variables and 2. they often cause collisions with other code used like libraries and pear classes using the same global variable names, which leads to unexpected behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM