如何根据laravel

时间:2018-03-07 12:14:23

标签: php laravel

我正在尝试根据laravel应用程序的控制器中的条件定义一个方法。但它显示以下错误。

  

Symfony \ Component \ Debug \ Exception \ FatalThrowableError   (E_PARSE)解析错误:语法错误,意外“if”(T_IF),期待   function(T_FUNCTION)或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');
    }
}

我有 lib.php ,我试图在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;

2 个答案:

答案 0 :(得分:1)

Man ...你在一个类中编写代码,但在任何方法之外。你不能这样做。也许你想把它放在__construct函数里面?

答案 1 :(得分:0)

使用类似下面的类而不是

<?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
    }
}

在控制器中使用该类:      

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');
    }
}