0

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!

4
  • 2
    And where is line 168 please? Commented Jun 24, 2010 at 10:10
  • " private $Login_Logged = $this->Extra_LoadSession("Login_Logged",false); " Commented Jun 24, 2010 at 10:12
  • There is no syntax error in this piece of code (according to php -l) Commented Jun 24, 2010 at 10:12
  • i was trying with the browser, this is very weird :s Commented Jun 24, 2010 at 10:13

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

10 Comments

I didn't understand sorry, how can i store a value on the var?
and that function will run automatically?
@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.
@cuss yes, it's run automatically when you create an object of the class. See php.net/manual/en/language.oop5.decon.php
+1 and correct answer ;) Thanks you and other developers for the help ;)
|
2

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?

1 Comment

An if can run the command above! you only need {} when you have more than one!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.