How to make php class available in function - php

I am using a third party class that works well as long as I use it in the main body of my PHP script. If I try to use it in a function that is called from main, it gets a "PHP Fatal error: Class 'RouterOS\Util' not found error". What do I need to do in the function so it can use the class?
<?php
require_once '/usr/local/sbrc/MTAPI/vendor/autoload.php';
...
GetNextRouter($loginData[0]['User'], $loginData[0]['Password'], $firstAddress[0]['IPAddress']);
...
}
function GetNextRouter($UserID, $Pass, $Address) {
$util = new RouterOS\Util($client = new RouterOS\Client($Address, $UserID, $Pass));
...
}
The error occurs on the $util = new RouterOS\Util line.

Adding
use PEAR2\Net\RouterOS;
solved my issue

Related

PHP: How to catch Fatal error: Cannot declare class [myclassname], because the name is already in use

I am implementing a plugin controller CLASS for client created custom plugins.
Since the names of the classes of each plugin could very well end up clashing with other plugins already installed, I want to make sure we don't get fatal errors when a new plugin comes in.
I want to report to the user that the new plugin is clashing with an already installed one.
So basically atm I testing with 2 files both containing exactly the same code and am getting:
Fatal error: Cannot declare class [myclassname], because the name is already in use
I have tried catching this with no success using:
try {
include_once $file;
} catch (ClosedGeneratorException|DOMException|ErrorException|IntlException|LogicException|BadFunctionCallException|BadMethodCallException|DomainException|InvalidArgumentException|LengthException|OutOfRangeException|PharException|ReflectionException|RuntimeException|OutOfBoundsException|OverflowException|PDOException|RangeException|UnderflowException|UnexpectedValueException|SodiumException $ex) {
echo "Unable to load file.";
}
All these I got from Lists of Throwable and Exception tree as of 7.2.0 in https://www.php.net/manual/en/class.exception.php
The manual specifies that:
The thrown object must be an instance of the Exception class or a
subclass of Exception. Trying to throw an object that is not will
result in a PHP Fatal Error.
Is it possible that this is not an object of instance/suclass of the Exception class?
What am I missing?
Short answer: no, you're not missing anything. Declaring a duplicate class name can't be caught in any version of PHP (including 8.0.0 as far as the alpha releases). See https://3v4l.org/2TLA3
For some additional background, PHP does sometimes move errors like these underneath the Throwable hierarchy, so that they can be detected at runtime. PHP 7 added support for catching an attempt to instantiate a missing class, and 7.3 added support for catching an attempt to extend a missing class. See https://3v4l.org/BDnm9 for a brief demo of those.
In the end, to avoid this fatal error I decide to parse the files for the first available class declaration using tokens as follows:
public function getClassInFile($filenpath) {
$src = $this->uncommentFile($filenpath);
$class ='';
if (preg_match('/class[\s\n]+([a-zA-Z0-9_]+)[\s\na-zA-Z0-9_]+\{/', $src, $matches)) {
$class = $matches[1];
}
return $class;
}
public function uncommentFile($filenpath) {
$fileStr = file_get_contents($filenpath);
$newStr = '';
$commentTokens = array(T_COMMENT);
if (defined('T_DOC_COMMENT'))
$commentTokens[] = T_DOC_COMMENT; // PHP 5
if (defined('T_ML_COMMENT'))
$commentTokens[] = T_ML_COMMENT; // PHP 4
$tokens = token_get_all($fileStr);
foreach ($tokens as $token) {
if (is_array($token)) {
if (in_array($token[0], $commentTokens))
continue;
$token = $token[1];
}
$newStr .= $token;
}
return $newStr;
}
In this way, I can check whether the class I am expecting to find is in there, or if the class in there already exists, thus avoiding to include_once altogether in these cases.
Problem solved.

Strange reflection behavior in php Laravel 4

This seems like a fairly simple reflection problem, yet I can't figure it our. I use Laravel 4.2 on Debian with PHP 5.6.6-1.
Basicly what happens is that I want to spawn a new object from a class in a Laravel QueueHandler like so:
$className = 'MyClass';
$myobject = new $className ();
and this doesn't work. I tried everything I can possibly think of and have no clue where to look. This code doesn;t work while it should:
<?php
use Pronamic\Twinfield\Secure\Config;
use Pronamic\Twinfield\Customer\CustomerFactory;
class TwinfieldQueueHandler {
private $twinfieldConfig = null;
...
try {
$twinfieldFactoryClass = 'CustomerFactory';
//returns 0
echo strcmp('CustomerFactory', $twinfieldFactoryClass);
//works
$test0 = new CustomerFactory ($this->twinfieldConfig);
//throws an exeption with message: "Class CustomerFactory does not exist"
$r = new ReflectionClass($twinfieldFactoryClass);
$test1 = $r->newInstanceArgs($this->twinfieldConfig);
//gives error PHP Fatal error: Class 'CustomerFactory' not found in {file} on line {line}
$test2 = new $twinfieldFactoryClass ($this->twinfieldConfig);
} catch (Exception $e) {
Log::error($e->getMessage());
}
Has anyone got any pointers on where to look and how to debug this?
ReflectionClass will ignore your current namespace and use statements completely. You have to specify the fully qualified name of the class:
$r = new ReflectionClass('Pronamic\Twinfield\Customer\CustomerFactory');
As a user points out on php.net:
To reflect on a namespaced class in PHP 5.3, you must always specify the fully qualified name of the class - even if you've aliased the containing namespace using a "use" statement.
Note that you could work around this by passing an object:
$test0 = new CustomerFactory ($this->twinfieldConfig);
$r = new ReflectionClass($test0);

Am I calling this class wrong?

I have this code in a file named server.class.php:
class server
{
function addPlayer($player)
{
//Stuff
}
}
Then, I have this in a file called send.php. These are lines 38-40:
require('/var/www/server/apply/server.class.php');
$server = new server;
$server->addPlayer($_POST['IGN']);
However, I get this error when I visit my page (Php.ini is set to show all errors):
Fatal error: Class 'server' not found in /var/www/server/apply/send.php on line 39
Line 39 is $server = new server;
What am I doing wrong? I have verified that the class file is in /var/www/server/apply/server.class.php.
$server = new server()
Missed the brackets

Class PDO not found when calling a singleton class

can anyone tell me what could cause this error "Fatal error: Class PDO not found"
when I call the singleton class like this: $db = db::krijgInstantie();
I use an mvc design and this error is weird, because I use the same code for another site
public static function krijgInstantie()
{
if (!self::$instantie)
{
$config = config::krijgInstantie();
$db_type = $config->config_waarden['database']['db_type'];
$hostnaam = $config->config_waarden['database']['db_hostnaam'];
$dbnaam = $config->config_waarden['database']['db_naam'];
$db_wachtwoord = $config->config_waarden['database']['db_wachtwoord'];
$db_gebruikersnaam = $config->config_waarden['database']['db_gebruikersnaam'];
$db_poort = $config->config_waarden['database']['db_poort'];
self::$instantie = new PDO("$db_type:host=$hostnaam;port=$db_poort;dbname=$dbnaam",$db_gebruikersnaam, $db_wachtwoord);
self::$instantie-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
return self::$instantie;
}
thanks, Richard
Your PHP installation is missing the PDO module. Check your PHP.ini.
See also: http://php.net/manual/en/pdo.installation.php

php and webservices

I have a wsdl file and i am trying to call it from a php class. I am using the following code:
<?php
include ("dbconn.php");
class dataclass
{
function getCountries()
{
$connection = new dbconn();
$sql = "SELECT * FROM tblcountries";
$dataset = $connection -> connectSql($sql);
return $dataset;
}
function getTest()
{
$connection = new dbconn();
$sql = mysql_query('CALL sp_getTest');
$dataset = $connection -> connectSql($sql);
return $dataset;
}
##-------------------------------------------CUSTOMER METHODS-------------------------------------------
function registerCustomer($username,$name,$surname,$password,$email,$country,$tel)
{
$connection = new dbconn();
$sql="INSERT INTO tblcustomer (customer_username, customer_password, customer_name, customer_surname,
customer_email, customer_country, customer_tel)
VALUES('$username','$name','$surname','$password','$email','$country','$tel')";
$dataset = $connection -> connectSql($sql);
}
ini_set("soap.wsdl_cache_enabled", "0");
// start the SOAP server - point to the wsdl file
$webservice = new SoapServer("http://localhost/dataobjects/myWebservice.wsdl", array('soap_version' => SOAP_1_2));
// publish methods
$webservice->addFunction("getCountries");
$webservice->addFunction("registerCustomer");
// publish
$webservice->handle();
}
?>
It is all the time giving me a problem with ini_set("soap.wsdl_cache_enabled", "0");
The error is:
Parse error: syntax error, unexpected T_STRING, expecting T_FUNCTION in C:\Program Files\xampplite\htdocs\dataobjects\dataClass.php on line 47
I believe it is because you have ini_set() call in the body of your class. Put it at the top of the file or in the constructor if you have one.
class dataClass
{
function registerCustomer()
{
// some stuff
}
ini_set(/*args*/); // it's illegal to put instructions in the body of the class
}
Now I see the whole thing. You probably want to close the class with a closing backet before line 47.
You let the parser think "0" is a string, and not a number, please remove the quotes!
Edit 1 If that wouldn't work, your error must be before that line, please post the full code for review.
Edit 2 The code you provided was running inside the class, you miss a bracket before the line with ini_set.
Move the last } in front of ini_set(...)
By the way, you said you want to call a web service, but you are creating a server which may be called by others.
To call a web service, try something like this:
try{
$client = new SoapClient($service, array('location' =>"http://example.org/myWebService"));
$parameter1 = new myWebServiceParameter();
$result = $client->myWebServiceFunction($parameter1);
} catch (Exception $e) {
// handle errors
}
myWebServiceParameter must be any class with a member variable foreach WSDL message attribute of the same name.
And myWebServiceFunction is the name of the web service method.

Categories