-1

I'm trying to define a method based on a condition in the controller of my laravel application. But it shows the following error.

Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_PARSE) Parse error: syntax error, unexpected 'if' (T_IF), expecting function (T_FUNCTION) or const (T_CONST)

HomeController.php

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class HomeController extends Controller
{
    if (!function_exists('curl_init')) :
        define('CURLOPT_URL', 1);
        function curl_init($url = false) {
            return new Curl($url);
        }
    endif;

    public function index(){

        return view('welcome');
    }
}

I have lib.php and I'm trying to achieve the same in laravel

if (!function_exists('curl_init')) :
    define('CURLOPT_URL', 1);
    define('CURLOPT_USERAGENT', 2);
    define('CURLOPT_POST', 3);
    define('CURLOPT_POSTFIELDS', 4);
    define('CURLOPT_RETURNTRANSFER', 5);

    function curl_init($url = false) {
        return new Curl($url);
    }


    function curl_close(&$ch) {
        unset($ch);
    }

    function curl_errno($ch) {
        return $ch->error;
    }

    function curl_error($ch_error) {
        return "Could not open socket";
    }

    function curl_getinfo($ch, $opt = NULL) {
        return $ch->info;
    }



endif;
tereško
  • 58,060
  • 25
  • 98
  • 150
NIKHIL NEDIYODATH
  • 2,703
  • 5
  • 24
  • 30

2 Answers2

1

Man... you are writing code inside a class but outside any method. You can't do that. Maybe you want to put that inside the __construct function?

Amarnasan
  • 14,939
  • 5
  • 33
  • 37
0

use a class like below instead of that

<?php
class Curl
{
    private $curl;

    public function __construct($url = false) {
        $this->curl = !function_exists('curl_init') ? $this->makeObj($url) : 
        curl_init($url);
    }

    private function makeObj($url)
    {
        // return new class
    }
}

use the class in your controller:

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Libs\Curl; // change this with your class path

class HomeController extends Controller
{

    public function index(){

        $curl = new Curl('http://stackoverflow.com');

        return view('welcome');
    }
}
Meysam Mahmoodi
  • 433
  • 5
  • 19