I just start learning PHP few days ago so forgive me if this question is a newbie one.
What is wrong with my declaration of CRAWLER_URI ? The env() isn't working outside a method and I don't know why.
namespace App\Http\Controllers;
use GuzzleHttp\Client;
class SpotifyController extends Controller
{
const CRAWLER_URI = env('CRAWLER_URI') . ':' . env('CRAWLER_PORT');
/**
* Send a GET to Crawler API
* #return a json crawled by an external API crawler
*/
public function fetch()
{
$client = new Client(['base_uri' => self::CRAWLER_URI]);
$response = $client->request('GET');
dd($response);
}
}
So, the issue here is that you can’t use a function as a class constant value:
According to the PHP manual:
The value must be a constant expression, not (for example) a variable, a property, or a function call.
There are many solutions to this problem, for example, if you really want it to be constant, you could use a define() statement like this:
define('CRAWLER_URI', env('CRAWLER_URI') . ':' . env('CRAWLER_PORT'));
and access it like this:
echo CRAWLER_URI;
Another method would be to use a static function:
private static function CRAWLER_URI() {
return env('CRAWLER_URI') . ':' . env('CRAWLER_PORT');
}
and access it like this:
echo $this->CRAWLER_URI();
Related
So, the question pretty much explains what i want. Here is the minimum code of what i am doing.
class AuthorizeController extends Controller
{
private $aNetEnvironment;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->aNetEnvironment = env('ANetEnvironment');
}
public function setEnvironment()
{
$controller = new AnetController\GetCustomerProfileController($request);
// $this->aNetEnvironment = SANDBOX
$response = $controller->executeWithApiResponse(
\net\authorize\api\constants\ANetEnvironment::$this->aNetEnvironment
);
}
}
Searching stackoverflow i got two options, have tried both with no luck.
Trying, {$this->aNetEnvironment} gives
syntax error, unexpected ')', expecting '('
Trying, $$this->aNetEnvironment gives
Object of class App\Http\Controllers\AuthorizeController could not be
converted to string
Edit:
Trying, ${$this->aNetEnvironment} gives
Access to undeclared static property:
net\authorize\api\constants\ANetEnvironment::$SANDBOX
Is there any other option ?
You could make use of the PHP's constant() helper. From the docs:
Signature:
constant ( string $name ) : mixed
Return the value of the constant indicated by name.
constant() is useful if you need to retrieve the value of a
constant, but do not know its name. I.e. it is stored in a variable or
returned by a function.
This function works also with class constants.
So in your case:
$response = $controller->executeWithApiResponse(
constant('\net\authorize\api\constants\ANetEnvironment::' . $this->aNetEnvironment)
);
To use class properties as variable variables in this way you need to start with a $ and wrap the property in {} e.g. ${$this->property} so you should be able to use the following in your controller:
\net\authorize\api\constants\ANetEnvironment::${$this->aNetEnvironment}
I struggle with this problem for a while - and the reason is probably trivial.
Background
I've created parser module for my Yii2 application so I can call it from other places (mobile app, etc.) to get data from various websites. There may be many parser classes, all implementing same interface.
Project structure
...
/modules
\_ parser
\_components
\_parsers
\_SampleParser.php
\_controllers
\_DefaultController.php
\_Parser.php
...
I've removed some code for better readability.
DefaultController.php:
namespace app\modules\parser\controllers;
use Yii;
use yii\web\Controller;
use app\modules\parser\components\parsers;
use app\modules\parser\components\parsers\SampleParser;
/**
* Default controller for the `parser` module
*/
class DefaultController extends Controller
{
private function loadParser($parserName){
return new SampleParser(); // if I leave this here, everything works okay
$className = $parserName.'Parser';
$object = new $className();
if ($object instanceof IParseProvider){
return $object;
}
}
...
public function actionIndex()
{
$url = "http://google.com";
$parser = 'Sample';
$loadedParser = $this->loadParser($parser);
$response = $loadedParser->parse($url);
\Yii::$app->response->format = 'json';
return $response->toJson();
}
...
SampleParser.php:
<?php
namespace app\modules\parser\components\parsers;
use app\modules\parser\models\IParseProvider;
class SampleParser implements IParseProvider {
public function canParse($url){
}
public function parse($url){
}
}
Right now everything works more or less ok, so I guess I'm importing correct namespaces. But when I remove return new SampleParser(); and let the object to be created by string name, it fails with error:
PHP Fatal Error – yii\base\ErrorException
Class 'SampleParser' not found
with highlighted line:
$object = new $className();
What am I doing wrong here? Thanks!
Try again with help of Yii:
private function loadParser($parserName)
{
return \yii\di\Instance::ensure(
'app\modules\parser\components\parsers\\' . $parserName . 'Parser',
IParseProvider::class
);
}
Remember that ensure() throws \yii\base\InvalidConfigException when passed reference is not of the type you expect so you need to catch it at some point.
If you are using PHP < 5.5 instead of IParseProvider::class you can use full class name with it's namespace.
P.S. remove use app\modules\parser\components\parsers; unless you have got class named parsers you want to use.
I have a class with namespace which require many other classes further . main class is
<?php
/**
* Deals with PDF document level aspects.
*/
namespace Aspose\Cloud\Pdf;
use Aspose\Cloud\Common\AsposeApp;
use Aspose\Cloud\Common\Product;
use Aspose\Cloud\Common\Utils;
use Aspose\Cloud\Event\SplitPageEvent;
use Aspose\Cloud\Exception\AsposeCloudException as Exception;
use Aspose\Cloud\Storage\Folder;
class Document
{
public $fileName = '';
public function __construct($fileName='')
{
$this->fileName = $fileName;
}
/**
* Gets the page count of the specified PDF document.
*
* #return integer
*/
public function getFormFields()
{
//build URI
$strURI = Product::$baseProductUri . '/pdf/' . $this->getFileName() . '/fields';
//sign URI
$signedURI = Utils::sign($strURI);
//get response stream
$responseStream = Utils::ProcessCommand($signedURI, 'GET', '');
$json = json_decode($responseStream);
return $json->Fields->List;
}
}
I am using this like this in index.php
<?
ini_set('display_errors', '1');
use Aspose\Cloud\Pdf;
$document=new Document;
echo $document->GetFormFields();
//or like this
echo Document::GetFormFields();
//also tried this
echo pdf::GetFormFields();
?>
Error
Fatal error: Class 'Document' not found in /var/www/pdfparser/asposetry/index.php on line 5
Document class path is Aspose/Cloud/Pdf/Document.php
attempt one
working if i use to include in index.php include(Aspose/Cloud/Pdf/Document.php) but then further namespace produce error. Very difficult to change every use namespace with include. can anybudy tell me the solution for this ??
thanks.
namespace Aspose\Cloud\Pdf;
class Document {
...
To use this class, you'll have to write
use Aspose\Cloud\Pdf\Document
You can also access it without a use statement, but then you'll have to write the full name every time:
$document=new Aspose\Cloud\Pdf\Document;
// Or if you're in a namespace, you'll have to do this:
$document=new \Aspose\Cloud\Pdf\Document;
You are trying to use the Document class that's inside the Aspose\Cloud\Pdf namespace, but you are actually using a Document class without a namespace. You have to use one of the following ways:
//Option one:
use Aspose\Cloud\Pdf\Document;
Document::getFormFields();
//Option two:
Aspose\Cloud\Pdf\Document::getFormFields();
Also note that you can't use Document::getFormFields() as a static function, because it is not static. You should make it static (by putting static between public and function) or use it on an object.
Someone could help me on the issue of referencing php files within the same project (calling classes) using "namespace","use" ( php v5.3 or higher)
[My Screenshoot][http://i.imgur.com/6GC4UUK.png?1]
Fatal error: Class 'Zoho\CRM\Common\HttpClientInterface' not found in
C:\root\zohocrm-master\src\Zoho\CRM\index.php on line 73
<?php namespace Zoho\CRM;
use Zoho\CRM\Common\HttpClientInterface;
use Zoho\CRM\Common\FactoryInterface;
use Zoho\CRM\Request\HttpClient;
use Zoho\CRM\Request\Factory;
use Zoho\CRM\Wrapper\Element;
.
.
.
public function __construct($authtoken, HttpClientInterface $client =null , FactoryInterface $factory = null )
{
$this->authtoken = $authtoken;
// Only XML format is supported for the time being
$this->format = 'xml';
$this->client = new HttpClientInterface();
$this->factory = $factory ;
$this->module = "Leads";
return $this;
}
Robinson, you are calling the class "Zoho\CRM\Common**HttpClientInterface**" from this position: "C:\root\zohocrm-master\src\Zoho\CRM**index.php**".
This means the way you are trying to use the namespace is not correct.
Remember, if you do:
use App\namespace\class_name
It means your class "class_name" has to be in a folder like this: App/namespace/.
So define very well the path to your class when you are calling use.
I have a Model.class.php and a Bag.class.php, the Bag class extends the Model class.
But when i try to call a function defined in Bag.class.php, it show a fatal error " Call to undefined function fill_entity() in"
bag.class.php :
class Bag extends Model{
public function __construct($table_name){
$this->table_name = $table_name;
}
public function fill_entity($row){
$this->id = $row['bagID'];
$this->name = $row['bagName'];
$this->price = $row['bagPrice'];
$this->url = $row['bagURL'];
$this->img_url = $row['bagImgURL'];
$this->mall_id = $row['mallID'];
$this->brand_id = $row['brandID'];
}
here's my php page where i call this function :
$bag = new Bag($bagtype);
$bag.fill_entity($row); <---- error on this line.
You're using the wrong syntax. PHP doesn't use dot notation, but rather -> (arrow/pointer notation)
Try using this:
$bag->fill_entity($row);
(The . is still used in PHP, but is used for string concatenation.)
Don't feel bad about missing this, I did it plenty of times when I first tackled PHP.
In PHP, it would be $bag->fill_entity($row); rather than $bag.fill_entity($row);.