tags:

views:

41

answers:

2

Hi, i'm new related to creating php class's and objects... I'm trying to make a class to comunicate with our company api.

When i'm calling a function to a variable, php hangs with error:

Parse error: syntax error, unexpected T_VARIABLE in /var/www/(...)/microdualapi.class.php  on line 168

Can anybody give me a light? :) The code is above:

if(!class_exists("Microdual")) class Microdual{

    // No caso de a sessão não estar iniciada, iniciar aqui a sessão
    //session_start();

    ################
    ################
    ################
    ################ Iniciar funcoes privadas ################

    private function Extra_LoadSession($varname,$otherwise){
        //return (!empty($_SESSION[$this->Session_Prefix . $varname])) ? $_SESSION[$this->Session_Prefix . $varname] : $otherwise;
        return "OLA";
    }
    private function Extra_SaveSession($varname,$value){
        $_SESSION[$Session_Prefix.$varname] = $value;
        return true;
    }
    /**
    * $this->Extra_PostRequest()    "Comunicar comandos com os servidores Microdual (enviar e receber)"
    *
    * @author   Jonas John
    * @link     "http://www.jonasjohn.de/snippets/php/post-request.htm"
    *
    * @param    url string  
    * @param    referer string  
    * @param    data    array   
    *
    * @return   array($header,content)
    */
    private function Extra_PostRequest($url, $referer, $_data) {

        // convert variables array to string:
        $data = array();    
        while(list($n,$v) = each($_data)){
            $data[] = "$n=$v";
        }    
        $data = implode('&', $data);
        // format --> test1=a&test2=b etc.

        // parse the given URL
        $url = parse_url($url);
        if ($url['scheme'] != 'http') { 
            die('Only HTTP request are supported !');
        }

        // extract host and path:
        $host = $url['host'];
        $path = $url['path'];

        // open a socket connection on port 80
        $fp = fsockopen($host, 80);

        // send the request headers:
        fputs($fp, "POST $path HTTP/1.1\r\n");
        fputs($fp, "Host: $host\r\n");
        fputs($fp, "Referer: $referer\r\n");
        fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
        fputs($fp, "Content-length: ". strlen($data) ."\r\n");
        fputs($fp, "Connection: close\r\n\r\n");
        fputs($fp, $data);

        $result = ''; 
        while(!feof($fp)) {
            // receive the results of the request
            $result .= fgets($fp, 128);
        }

        // close the socket connection:
        fclose($fp);

        // split the result header from the content
        $result = explode("\r\n\r\n", $result, 2);

        $header = isset($result[0]) ? $result[0] : '';
        $content = isset($result[1]) ? $result[1] : '';

        // return as array:
        return array($header, $content);
    }
    /**
    * $this->API_Comunicate()   "Comunicar comandos com os servidores Microdual (enviar e receber)"
    *
    * @param    data    array   "Colocar as variaveis que deseja passar à plataforma (Ver Lista completa de variaveis no Inicio)"
    *
    * @return   array or void (false)
    */
    private function API_Comunicate($data){
        list($header, $content) = Extra_PostRequest($Geral_URLAPI, "http://".$_SERVER["SERVER_NAME"]."/" , $data);
        if(!empty($content)){
            return json_decode($content);
        }else{
            return false;
        }
    }


    ################
    ################
    ################
    ################ Iniciar funcoes Públicas ################

    /**
    * $this->IsLogged() "Verificar se está autenticado no servidor (primeiro localmente, e depois liga ao servidor)"
    *
    * @return   void
    */
    public function IsLogged(){
        if($logged) return true;
        $logged = Extra_LoadSession("Login_Logged",false);
        if($logged){
            return true;
        }else{
            // Conectar ao servidor
            $dados = API_Comunicate(array());
            if($dados!==false){
                if(!empty($dados['auth']['logged'])){
                    return $dados['auth']['logged'];
                }else{
                    return false;
                }
            }else{
                return false;
            }
        }
    }

    /**
    * $this->Login()    "Executar o Login nos servidores Microdual"
    *
    * @param    username    string  "Colocar aqui o nome de utilizador da sua conta em www.microdual.com"
    * @param    password    string  "Colocar aqui a password da sua conta em www.microdual.com"
    *
    * @return   void
    */
    public function Login($username,$password){
        if(empty($username) || empty($password)) return false;
        if($this->IsLogged()) return true;

    }


    ################
    ################
    ################
    ################ Iniciar variaveis da class (is buscar valor à sessão no caso de existir) ################

    private $Session_Prefix = "PREFFIX_";
    private $Geral_URLAPI = "http://www.MYSITE.com/MYapi";
    private $Login_Logged = $this->Extra_LoadSession("Login_Logged",false);


};

thanks in advance!

+2  A: 

To start, wrap the contents of your if in {

if(!class_exists("Microdual")) { class Microdual{

and add an extra closing } at the end of the if

};
}

Can a class property be initialised in this way?

private $Login_Logged = $this->Extra_LoadSession("Login_Logged",false);

or should it be initialized by the constructor?

Mark Baker
An if can run the command above! you only need {} when you have more than one!
CuSS
thanks for your answer :) +1
CuSS
The downvote wasn't mine and I wouldn't have voted it down, but this answer is not really correct, is it? The `{` `}` are good style, but not needed.
Pekka
+6  A: 

You say this is the offending line:

private $Login_Logged = $this->Extra_LoadSession("Login_Logged",false); 

You can't pre-populate a class variable by calling a method: A class definition is static. No $this exists at the time of the class definition, and no code can be executed.

You'll have to set that variable in your constructor:

private $Login_Logged;

function __construct()
 {
   $this->Login_Logged = $this->Extra_LoadSession("Login_Logged",false); 

 }

PHP Manual on constructors and destructors

Pekka
I didn't understand sorry, how can i store a value on the var?
CuSS
and that function will run automatically?
CuSS
@cuss you can't preset a variable to be the result of a function call. Just add the above `__construct` function to your class, it will do what you need. If you already have a `__construct` function, add the line in there.
Pekka
@cuss yes, it's run automatically when you create an object of the class. See http://www.php.net/manual/en/language.oop5.decon.php
Pekka
+1 and correct answer ;)Thanks you and other developers for the help ;)
CuSS
On more thing pekka, how do i create a class inside another class?Example: $Myclass=new Myclass(); $Myclass->Myotherclass->Mysubclassfunction();
CuSS
@cuss You can create an object and store it as a property of the mother class: `$this->Myotherclass = new Myotherclass();`
Pekka
On the constructor function?So... i have to create an separately class, right? (sorry to boring you)
CuSS
@cuss yes. You can't nest classes. You can only have an object of a certain class as a property (= variable) in another class. That child object can again have a property ... etc. But you can't define this in the class definition, you have to create the child objects in the constructor.
Pekka
Ok, very thank you ;) And sorry my english.You're the man!
CuSS
Pekka, sorry to boring you again, can you help me with this (http://stackoverflow.com/questions/3110841/php-curl-isnt-storing-the-session-cookie-how-to-fix-this) question?
CuSS