Is there a way on including a file at the beginning of a class for all methods to use. The example below is a simplified version of what I am trying to achieve. Currently I have to include the file within every method.
Example Logic (not working)
class Myclass
{
protected require_once 'folerd1/folder2/pear/HTTP/Request2.php'; // this does not work
public function aMethod()
{
$request = new HTTP_Request2('http://example1.com/', HTTP_Request2::METHOD_GET);
try {
$response = $request->send();
if (200 == $response->getStatus()) {
echo $response->getBody();
} else {
echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
$response->getReasonPhrase();
}
} catch (HTTP_Request2_Exception $e) {
echo 'Error: ' . $e->getMessage();
}
}
public function aMethod1()
{
$request = new HTTP_Request2('http://example2.com/', HTTP_Request2::METHOD_GET);
try {
$response = $request->send();
if (200 == $response->getStatus()) {
echo $response->getBody();
} else {
echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
$response->getReasonPhrase();
}
} catch (HTTP_Request2_Exception $e) {
echo 'Error: ' . $e->getMessage();
}
}
// more methods
}
2 solution
1) require_once taken outside from class
require_once 'folerd1/folder2/pear/HTTP/Request2.php';
class Myclass
{
2) Include in the construct
public function __construct() {
require_once 'folerd1/folder2/pear/HTTP/Request2.php';
}
But it is better first option
The best way is to look at autoloading standard http://www.php-fig.org/psr/psr-0/
Have you tried this? I don't know what's your Request2.php file content. So my code is only a PoC!
require 'folerd1/folder2/pear/HTTP/Request2.php';
class Myclass
{
public function aMethod()
{
$request = new Request2('http://example1.com/', Request2::METHOD_GET);
try {
$response = $request->send();
if (200 == $response->getStatus()) {
echo $response->getBody();
} else {
echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
$response->getReasonPhrase();
}
} catch (Request2_Exception $e) {
echo 'Error: ' . $e->getMessage();
}
}
public function aMethod1()
{
$request = new Request2('http://example2.com/', Request2::METHOD_GET);
try {
$response = $request->send();
if (200 == $response->getStatus()) {
echo $response->getBody();
} else {
echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
$response->getReasonPhrase();
}
} catch (Request2_Exception $e) {
echo 'Error: ' . $e->getMessage();
}
}
}
As I commented out, just require the file in the constructor of the PHP class:
class Myclass{
function Myclass(){
require_once('folerd1/folder2/pear/HTTP/Request2.php');
}
I have not checked this, but it MIGHT be possible that what you're just doing is including it not only for all the class to see, but the entire script. Please, check that out if it is a problem for you. If not, the other 2 solutions might end up doing the same.
Cheers
Related
When I try and unserialize the following string:
a:3:{i:0;s:19:\"Sales+%2F+Customers\";i:1;s:78:\"Micro+Business+%28less+than+10+employees+%26+turnover+under+%C2%A32+million%29\";i:2;s:13:\"Manufacturing\";}
It returns false and I get the following warning:
WARNING: Error at offset 9 of 158 bytes
It was generated by calling serialize on an array though and looks valid to me though, I don't understand what the problem is?
The slashes aren't valid in this case, use stripslashes(). Demo code below:
<pre>
<?php
$x = "a:3{i:0;s:19:\"Sales+%2F+Customers\";i:1;s:78:\"Micro+Business+%28less+than+10+employees+%26+turnover+under+%C2%A32+million%29\";i:2;s:13:\"Manufacturing\";}";
echo "unserializing $x: " . PHP_EOL;
try {
print_r(unserialize($x));
echo PHP_EOL;
} catch (\Exception $e) {
echo $e->getMessage() . PHP_EOL;
}
$y = "a:3{i:0;s:19:\\\"Sales+%2F+Customers\\\";i:1;s:78:\\\"Micro+Business+%28less+than+10+employees+%26+turnover+under+%C2%A32+million%29\\\";i:2;s:13:\\\"Manufacturing\\\";}";
echo "unserializing $y: " . PHP_EOL;
try{
print_r(unserialize($y));
echo PHP_EOL;
} catch (\Exception $e) {
echo $e->getMessage() . PHP_EOL;
}
echo "unserializing stripslashes($y): " . PHP_EOL;
try{
print_r(unserialize(stripslashes($y)));
} catch (\Exception $e) {
echo $e->getMessage() . PHP_EOL;
}
?>
</pre>
I've got a Search class, which has
public function __construct($isNewIndex = false) {
setlocale(LC_CTYPE, 'ru_RU.UTF-8');
$analyzer = new Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8_CaseInsensitive();
$morphy = new Isi_Search_Lucene_Analysis_TokenFilter_Morphy('ru_RU');
$analyzer->addFilter($morphy);
Zend_Search_Lucene_Analysis_Analyzer::setDefault($analyzer);
Zend_Search_Lucene_Search_QueryParser::setDefaultEncoding('utf-8');
//if it's true, then it creates new folder to the path in $_indexFieles;
if ($isNewIndex) {
$this->_indexes[$this->_key] = Zend_Search_Lucene::create(Yii::getPathOfAlias('application.' . $this->_indexFiles), true);
} else {
$this->_indexes[$this->_key] = Zend_Search_Lucene::open(Yii::getPathOfAlias('application.' . $this->_indexFiles));
}
}
public function find($query, $eventId)
{
try
{
Zend_Search_Lucene_Search_QueryParser::setDefaultOperator(Zend_Search_Lucene_Search_QueryParser::B_AND);
$query = "($query) AND (event_id:$eventId)";
Zend_Search_Lucene::setResultSetLimit(self::ACCREDITATION_LIMIT);
return $this->_indexes[$this->_key]->find("{$query}");
}
catch (Zend_Search_Lucene_Search_QueryParserException $e)
{
echo "Query syntax error: " . $e->getMessage() . "\n";
}
catch (Exception $e)
{
echo $e->getMessage(). "\n";
}
}
I've got a record with name Test, when I'm looking for Test it works, but can't find this record with request test
Code example:
$s = new Search();
$s->find('test', 1232);//no results
I found a solution, the problem was that I was saving fields (name, etc.) as keyword, I changed it to text, and now it's working perfectly.
Here's the code I'm currently working with:
try {
// Use '' al default
if(isset($_GET['url'])) {
$url = $_GET['url'];
unset($_GET['url']);
} else {
$url = '';
}
$proxy = new Proxy();
echo $proxy->run($url, $_GET, $_POST);
} catch(Exception $e) {
echo 'Error: '.$e->getMessage();
}
This is the part of the code I'm having issues with specifically:
echo $proxy->run($url, $_GET, $_POST);
This will echo a website after running it through a proxy. What I'm trying to do is replace <head> with the following text: <head> this is a test
So, I tried changing to code to this:
try {
// Use '' al default
if(isset($_GET['url'])) {
$url = $_GET['url'];
unset($_GET['url']);
} else {
$url = '';
}
$proxy = new Proxy();
$proxy_replace = str_replace('<head>','<head> this is a test',$proxy);
echo $proxy_replace->run($url, $_GET, $_POST);
} catch(Exception $e) {
echo 'Error: '.$e->getMessage();
}
But this is the error I'm getting:
Catchable fatal error: Object of class Proxy could not be converted to string in /home/username/public_html/testfolder/index.php on line 249
Any help with this would be greatly appreciated....
You need to perform the replacement on the downloaded HTML, not on the Proxy instance. Something like this should work:
try {
// Use '' al default
if(isset($_GET['url'])) {
$url = $_GET['url'];
unset($_GET['url']);
} else {
$url = '';
}
$proxy = new Proxy();
$html = $proxy->run($url, $_GET, $_POST);
$html_replace = str_replace('<head>','<head> this is a test',$html);
echo $html_replace;
} catch(Exception $e) {
echo 'Error: '.$e->getMessage();
}
I'm trying to display some data this way from mysql in php:
CompteDAO.php
<?php
namespace DAO;
include_once(__DIR__ . '/bdConfig.php');
class CompteDAO
{
public $bdd;
public function getList(){
$this->bdd = new \DAO\bdConfig();
$requete = $this->bdd->bd->prepare('SELECT * FROM compte');
$requete->execute();
return $requete;
}
}
?>
bdConfig.php
<?php
namespace DAO;
use PDO;
class bdConfig
{
public $bd;
public function __construct()
{
try
{
$this->bd = new PDO('mysql:host=127.0.0.1;dbname=d', 'root', '');
}
catch (Exception $e)
{
die('Erreur: ' . $e->getMessage());
}
}
}
?>
index.php
$daoCompte = new \DAO\CompteDAO();
$comptes = $daoCompte->getList();
while ($data = $this->comptes->fetch()) {
echo '<td>' . $data['CIN'] . '</td>';
}
But, doing this, I get no result. (Knowing that my database isn't empty) I think that the probelm is becoming from the getList return value, but I couldn't be able to found why and how to resolve it.
How do I fix this, please ?
try this:
$daoCompte = new \DAO\CompteDAO();
$comptes = $daoCompte->getList();
$dataArray = $comptes->fetchAll(PDO::FETCH_ASSOC);
foreach ($dataArray as $data) {
echo '<td>' . $data['CIN'] . '</td>';
}
you are not using class and you have no class property name $comptes. So $this->comptes is invalid.
How to catch an error from a SOAP?
How can I avoid the fatal error and convert it to my own error.. In this example it's a SERVER_BUSY
code
class Validate_vatno {
private $client = null;
private $options = array(
'debug' => false
);
public function __construct(){
$this->client = new SoapClient('http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl', array('trace' => true));
}
public function check($country, $vatno){
$result = $this->client->checkVat(array(
'countryCode' => $country,
'vatNumber' => $vatno
));
if(!empty($this->options['debug'])){
echo '<pre>'.htmlentities($this->client->__getLastResponse()).'</pre>';
}
if($result->valid){
list($denomination, $name) = explode(' ', $result->name, 2);
return array(
'denomination' => utf8_decode($denomination),
'name' => ucwords(utf8_decode($name)),
'address' => ucwords(utf8_decode($result->address)),
);
}
else{
return array();
}
}
}
$vatValidation = new Validate_vatno();
if($return = $vatValidation->check('DK', 33214944)){
echo '<h1>valid one!</h1>';
echo 'denomination: ' . $return['denomination']. '<br/>';
echo 'name: ' . $return['name']. '<br/>';
echo 'address: ' . $return['address']. '<br/>';
}
else{
echo '<h1>Invalid VAT</h1>';
}
error
Fatal error: Uncaught SoapFault exception: [soapenv:Server] { 'SERVER_BUSY' } in /var/www/
Review how to handle exceptions
Throwing and Catching a Exception
<?php
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
else return 1/$x;
}
try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
// Continue execution
echo 'Hello World';
?>