How to reference a Class Method using an array variable in PHP7? - php

I've moved from PHP5 to PHP7.
The following code no longer works.
<?php
class sandbox {
function doit() {
$method = array('name' => 'testresponse');
return $this->$method['name']();
}
function testresponse(){
return "Hi!";
}
}
$h = new sandbox();
echo "Hello, " . $h->doit();
I'm wondering what is the new syntax for this?
Here are the PHP errors I'm getting
A PHP Error was encountered Severity: Notice
Severity: Notice
Message: Array to string conversion
Filename: front/sandbox.php
Line Number: 20
And
Fatal error: Uncaught Error: Function name must be a string in /var/www/application/controller/sandbox.php:20 Stack trace: #0

Change this
return $this->$method['name']();
to this
return $this->{$method['name']}();

Related

Methods with the same name

My webpage gives the "methods with the same name as their class will not be constructors in a future version of php" error with the below code.
When I change the "function settings()" to "function __construct()", the web page gives a fatal error.
Fatal error: Uncaught Error: Call to undefined method validator::settings() in /home/mertcek1563/public_html/rmd2015/sdwf/validator.php:11
Stack trace:
#0 /home/mertcek1563/public_html/rmd2015/z_common.php(103): validator->__construct()
#1 /home/mertcek1563/public_html/rmd2015/z_core.php(22): include('/home/mertcek15...')
#2 /home/mertcek1563/public_html/rmd2015/index.php(2): include('/home/mertcek15...')
#3 {main}
thrown in /home/mertcek1563/public_html/rmd2015/sdwf/validator.php on line 11
How I can fix this code?
class settings
{
var $settings = array();
function settings(){
$this->settings["price"]=array();
$this->settings["price"]["dot"]=".";
$this->settings["price"]["decimals"]=6;
$this->settings["date"]=array();
$this->settings["date"]["delimiter"]="/";
$this->settings["date"]["format"]="dd/mm/yyyy";
$this->settings["number"]=array();
$this->settings["number"]["dot"]=".";
$this->settings["number"]["decimals"]=6;
}
}
Then I end up with fatal error:
Fatal error: Uncaught Error: Call to undefined method
validator::settings() in
/home/mertcek1563/public_html/rmd2015/sdwf/validator.php:11
<?
include_once("settings.php");
class validator extends settings
{
var $errors = array();
var $required = array();
function __construct(){
$this->settings();
}

ReactPHP get_class() expects parameter 1 to be object, string given

I am getting this error code:
PHP Warning: get_class() expects parameter 1 to be object, string
given in /phalcon/vendor/clue/block-react/src/functions.php on line 90
PHP Fatal error: Uncaught UnexpectedValueException: Promise rejected
with unexpected value of type in
/phalcon/vendor/clue/block-react/src/functions.php:89 Stack trace:
0 /phalcon/vendor/clue/block-react/src/functions.php(198): Clue\React\Block\await(NULL, Object(React\EventLoop\StreamSelectLoop),
NULL)
1 /phalcon/app/tasks/RunTask.php(96): Clue\React\Block\awaitAll(NULL, Object(React\EventLoop\StreamSelectLoop))
I'm building my promises with the following code:
$promises[] = $this->getTrades($rule->id, $exchange->id)
->then(
function ($trades) use ($handleTrades) {
foreach ($trades as $trade) {
$handleTrades[] = $trade;
}
}
);
The function is like this:
private function getTrades($rule, $exchange) {
$deferred = new React\Promise\Deferred();
//...
if (empty($trades->count())) {
$deferred->reject("No trades found for rule $rule");
} else {
$deferred->resolve($trades);
}
return $deferred->promise();
}
How do I solve this?
The real reason is Fatal error: Uncaught UnexpectedValueException, not the warning. As you can see the clue/reactphp-block library expects an Exception in your reject function. Try:
$deferred->reject(new \Exception("No trades found for rule $rule"));
As Furgas mentioned above I needed to add the error handling function in the promise.

codeigniter 2 with doctrine 2 - I can insert data in to tables but I can't get data back

I am still trying to study doctrine so I am following online tutorial by that I could insert data in to a mysql table. like this.
public function createObjects() {
// create a new user object
$user = new Entities\User;
$user->setFirstName('Joel');
$user->setLastName('Verhagen');
$user->setPassword(md5('Emma Watson'));
$this->doctrine->em->persist($user);
$this->doctrine->em->flush();
}
Then I tried to get the data back like this.
public function testing() {
// $user = new Entities\User;
$article = new Entities\Article;
$firstname = $this->doctrine->em->getRepository($article);
$products = $firstname->findAll();
foreach ($products as $product) {
echo sprintf("-%s\n", $product->getContent());
}
}
But I am getting following errors can some one help me on this?
Severity: Warning
Message: ltrim() expects parameter 1 to be string, object given
Filename: ORM/EntityManager.php
Severity: Warning
Message: class_parents(): object or string expected
Filename: Mapping/RuntimeReflectionService.php
Severity: Warning
Message: array_reverse() expects parameter 1 to be array, boolean given
Filename: Mapping/AbstractClassMetadataFactory.php
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: Mapping/AbstractClassMetadataFactory.php
Fatal error: Uncaught exception 'ReflectionException' with message 'Class does not exist' in E:\xampp\htdocs\shoping\application\libraries\Doctrine\Common\Persistence\Mapping\RuntimeReflectionService.php:73 Stack trace: #0 E:\xampp\htdocs\shoping\application\libraries\Doctrine\Common\Persistence\Mapping\RuntimeReflectionService.php(73): ReflectionClass->__construct('') #1 E:\xampp\htdocs\shoping\application\libraries\Doctrine\ORM\Mapping\ClassMetadataInfo.php(867): Doctrine\Common\Persistence\Mapping\RuntimeReflectionService->getClass(NULL) #2 E:\xampp\htdocs\shoping\application\libraries\Doctrine\ORM\Mapping\ClassMetadataFactory.php(517): Doctrine\ORM\Mapping\ClassMetadataInfo->initializeReflection(Object(Doctrine\Common\Persistence\Mapping\RuntimeReflectionService)) #3 E:\xampp\htdocs\shoping\application\libraries\Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory.php(300): Doctrine\ORM\Mapping\ClassMetadataFactory->initializeReflection(Object(Doctrine\ORM\Mapping\ClassMetadata), Object(Doctrine\Common\Pe in E:\xampp\htdocs\shoping\application\libraries\Doctrine\Common\Persistence\Mapping\RuntimeReflectionService.php on line 73
Tried and tried and at last I found a way to go.
public function testing() {
// $user = new Entities\User;
$article = new Entities\Article;
$firstname = $this->doctrine->em->getRepository('Entities\Article');
$products = $firstname->findAll();
foreach ($products as $product) {
echo sprintf("-%s\n", $product->getContent());
}
// $products = $article->getContent();
// echo $products.'fdsf';
}

codeigniter class error

For some reason i cant get my model to work.. never had this problem before.
function overview($userid)
{
// Load needed model
$this->load->model('budget_model');
$data['month_budget'] = $this->budget_model->get_monthly_budget($userid);
if(isset($_POST['submit']))
{
foreach($_POST as $key => $value)
{
if(is_numeric($key))
{
$this->buget_model->update_buget($key,$value);
echo "DONE";
}
}
echo "<pre>";
print_r($_POST);
echo "</pre>";
}
$data['main'] = 'super_admin/budget_edit_overview_view';
$this->load->view('default/main_view',$data);
}
The model works fine with "$this->budget_model->get_monthly_budget($userid);" but i keep getting thir error,
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Admin::$buget_model
Filename: controllers/admin.php
Line Number: 166
Fatal error: Call to a member function update_buget() on a non-object
in /Applications/MAMP/htdocs/therace/application/controllers/admin.php
on line 166
The model method,
function update_buget($id,$budget)
{
$this->db->where('id', $id);
// Update the month budget
$data = array(
'month_goal' => $budget
);
$this->db->update('budget_month', $data);
return true;
}
Read the error message carefully:
Message: Undefined property: Admin::$buget_model
Did you make a typo and actually mean $budget_model?
edit: There seems to be a lot of budget vs. buget in your code. I suggest a spellchecker.
You have made a typing error in line 166.
It is $this->budget_model->update_buget($key,$value);
not $this->buget_model->update_buget($key,$value);

How to handle erroneous argument type in this situation?

I'd like to use stdClass to store options for some methods, instead of passing huge lists of variables (inspired by javascript-style coding)
However, I'd like to make sure I'm always getting an instance of stdClass as an argument. I know I can add a hint in the argument (gb::search below) but when I deliberately try to break it, I'm not sure how to handle the error.
Any tips?
class gb extends CI_Model {
protected $searchtypes = array('full','partial');
protected $endpoint = "https://local.endpoint";
function __construct() {
parent::__construct();
// sample search
$options = new stdClass();
$options->term = 'sample search';
$options->type = 'full';
$this->search($options);
}
function clean_term($term){
$term = trim($term);
return $term;
}
function search(stdClass $options){
$term = $options->term;
$type = $options->type;
// make sure we're doing a valid search
if (!$term || !in_array($type, $this->searchtypes)) {
return false;
}
$term = $this->clean_term($term); // etc
}
The error it throws is something like:
A PHP Error was encountered
Severity: 4096
Message: Argument 1 passed to gb::search() must be an instance of stdClass, null given, called in /application/models/gb.php on line 20 and defined
Filename: models/gb.php
Line Number: 29
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: models/gb.php
Line Number: 31
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: models/gb.php
Line Number: 32
Any ideas how to approach this from a CodeIgniter point of view?
if I remember - mistyped argument should raise E_RECOVERABLE_ERROR, so, it triggers error handler but execution continues. So, you have two options basically.
One is to throw exception in error handler when E_RECOVERABLE_ERROR is encountered. To halt execution.
Another - check type with instanceof stdClass and do what you suppose - raise exception or return something.
UPDATE In your case your framework (CI is for CodeIgniter?) sets error handler (somewhere using set_error_handler). So, after logging or printing error message execution continues. (If there was not handler you would get fatal error). Just test type of argument manually:
function search(stdClass $options){
// test type for sure, because of recoverable error
if (!($options instanceof stdClass)) {
return false; // or throw new InvalidArgumentException('Parameter should be instance of stdClass');
}
$term = $options->term;
$type = $options->type;
// make sure we're doing a valid search
if (!$term || !in_array($type, $this->searchtypes)) {
return false;
}
$term = $this->clean_term($term); // etc
}

Categories