I have a class like this:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
class api {
function __construct($_GET) {
if ($_GET['method'] == "add") {
$this->add();
}
else if ($_GET['method'] == "subtract") {
$this->subtract();
}
}
function add() {
return "Adding!";
}
function subtract() {
return "Subtracting!";
}
}
$api = new api($_GET);
echo $api;
?>
When I send a URL from the browser of : test.php?method=add
I’m not getting any output or error messages. What I am missing?
Your construct function is not returning anything, only your other functions. Try this.
Class api {
function __construct($_GET) {
if ($_GET['method'] == "add") {
$this->message = $this->add();
}
else if ($_GET['method'] == "subtract") {
$this->message = $this->subtract();
}
}
function add() {
return "Adding!";
}
function subtract() {
return "Subtracting!";
}
}
$api = new api($_GET);
echo $api->message;
Change your contructor to this...
function __construct() {
if(isset($_GET)){
if($_GET['method']== "add") {
$this->add();
}
else if($_GET['method'] == "subtract"){
$this->subtract();
}}
}
You don't have to pass $_GET into the construct, as its a super global and is available everywhere, all the time
Try this
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
class api {
function __construct() {
if ($_GET['method'] == "add") {
return $this->add();
}
else if ($_GET['method'] == "subtract") {
return $this->subtract();
}
}
function add() {
return "Adding!";
}
function subtract() {
return "Subtracting!";
}
}
$api = new api();
echo $api->__construct();
?>
__construct() is the class method so in order to get the returned value from this method you have to use it this way $api->__construct()
Related
I have an API in the Yii framework where I'm sending a response but in response not returning data whereas in echo & var_dump() coming data but not return.
Please give me a solution to what is my mistake in code whereas working with simple echo. Thanks
This is my code
protected function findModel($api_offer_id)
{
$model = Offer::model()->findByAttributes(array("api_offer_id" => $api_offer_id));
if ($model) {
return $model;
} else {
return json_encode(array('status'=>0,'error_code'=>400,'message'=>'Bad request'),JSON_PRETTY_PRINT);
exit;
}
}
public function actionUpdate_status($api_offer_id)
{
$api_offer_id = $_REQUEST['api_offer_id'];
$status = $_REQUEST['status'];
if($api_offer_id) {
$model = $this->findModel($api_offer_id);
$model->status = self::offerStatus($status);
if ($model->save()) {
return json_encode(array('status'=>1,'data'=>array_filter($model->attributes)),JSON_PRETTY_PRINT);
} else {
return json_encode(array('status'=>0,'error_code'=>400,'errors'=>$model->errors),JSON_PRETTY_PRINT);
}
}
}
public static function offerStatus($status) {
if($status == "Accepted") {
return "1";
}
if($status == "Rejected") {
return "2";
}
}
You are missing
public function actionUpdate_status($api_offer_id)
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
...
return [
'status'=>1,
'data'=>array_filter($model->attributes)
];
to tell Yii that this is an application/json response. You don't even need the json_encode(). See the docs
Hy,
i started learning PHP and i created a simple MVC Style Codebase.
The Script just generates a random number and displays this numer. I also write a function to display the number shown before but it does not work. The value is empty. Can you help me out, i have no clue whats wrong and there is no php error thrown.
view.php
<?php
class View
{
private $model;
private $view;
public function __construct()
{
$this->model = new Model();
}
public function output()
{
echo 'Current Entry: ';
echo $this->model->getData();
echo '<br />';
echo 'Update';
echo '<br />';
echo 'Last';
}
public function getModel()
{
return $this->model;
}
}
controller.php
<?php
class Controller
{
private $model;
private $view;
public function __construct($view)
{
$this->view = $view;
$this->model = $this->view->getModel();
}
public function get($request)
{
if (isset($request['action']))
{
if ($request['action'] === 'update')
{
for ($i = 0; $i<6; $i++)
{
$a .= mt_rand(0,9);
}
$this->model->setData($a);
}
elseif ($request['action'] === 'preview')
{
$this->model->setLast();
}
else
{
$this->model->setData('Wrong Action');
}
}
else
{
$this->model->setData('Bad Request');
}
}
}
model.php
<?php
class Model
{
private $data;
private $last;
public function __construct()
{
$this->data = 'Default';
}
public function setData($set)
{
if ( ! (($set == 'Wrong Action') && ($set == 'Bad Request')))
{
$this->last = $this->data;
}
$this->data = $set;
}
public function getData()
{
return $this->data;
}
public function setLast()
{
$this->data = $this->last;
}
public function getLast()
{
return $this->last;
}
}
index.php
<?php
require_once 'controller.php';
require_once 'view.php';
require_once 'model.php';
$view = new View();
$controller = new Controller($view);
if (isset($_GET) && !empty($_GET)) {
$controller->get($_GET);
}
$view->output();
Are there any other, bad mistakes in the Script?
Any input very welcome! :)
The problem with your code is that PHP does not preserve variable values between requests, therefore, when you set your $model->last value here:
$this->last = $this->data;
It gets reset on your next request.
You may want to store $last value in a session or a cookie instead. Something like:
$_SESSION['last'] = $this->data;
And then when you are instantiating your model you could initialize it with a value stored in a session if available:
index.php - add session_start() at the beginning
model.php:
public function __construct()
{
$this->data = isset($_SESSION['last']) ? $_SESSION['last'] : 'Default';
}
public function setData($set)
{
$this->data = $set;
if ( ! (($set == 'Wrong Action') && ($set == 'Bad Request')))
{
$_SESSION['last'] = $this->data;
}
}
controller.php
elseif ($request['action'] === 'preview')
{
//Remove this
//$this->model->setLast();
}
I have a system that was designed to do a kind of cascading - get the sequence of methods called upon success of the previous condition.
The example is the below code, which I presume it's not a best practice for doing this, so would be great if I could get some suggestions to refactor this, probably using a design pattern or a different than this system.
<?php
class Model
{
public function isOk()
{
return true;
}
}
class OtherClass
{
public function isOk()
{
return true;
}
}
class AnotherClass
{
public function verifies()
{
return true;
}
}
class Sequence
{
public function fire()
{
$model = new Model();
if($model->isOk()) {
$otherclass = new OtherClass();
if($otherclass->isOk()) {
$anotherclass = new AnotherClass();
if($anotherclass->verifies()) {
echo "We're done with the sequence.";
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
}
$sequence = new Sequence();
echo $sequence->fire();
?>
I would avoid deep nesting of if/else statements to enhance the readability. One way is to use early return:
class Test1
{
public function isOk()
{
echo 'Test1';
return true;
}
}
class Test2
{
public function isOk()
{
echo 'Test2';
return true;
}
}
class Sequence
{
public function fire()
{
$test1 = new Test1();
if (!$test1->isOk()) {
return false;
}
$test2 = new Test2();
if (!$test2->isOk()) {
return false;
}
echo "We're done with the sequence.";
return true;
}
}
If you need it more dynamically you could use call_user_func or call_user_func_array.
class Sequence
{
protected $sequence = array(
array('Test1', 'isOk'),
array('Test2', 'isOk'),
);
public function fire()
{
foreach ($this->sequence as $callback) {
if (!call_user_func(array(new $callback[0], $callback[1]))) {
return false;
}
}
echo "We're done with the sequence.";
return true;
}
}
So I have a class I'm working on to manage PHP sessions, here's the class:
class SessionManagement {
public static function sessionStarted() {
if(session_id() == '') {
return false;
} else {
return true;
}
}
public static function sessionExists($session) {
if(sessionStarted() == false) {
session_start();
}
if(isset($_SESSION[$session])) {
return true;
} else {
return false;
}
}
public static function setSession($session, $value) {
if(sessionStarted() != true) {
session_start();
}
$_SESSION[$session] = $value;
if(sessionExists($session) == false) {
throw new Exception('Unable to Create Session');
}
}
public static function getSession($session) {
if(isset($_SESSION[$session])) {
return $_SESSION[$session];
} else {
throw new Exception('Session Does Not Exist');
}
}
}
Now trying this...
try {
SessionManagement::setSession('Foo', 'Bar');
echo SessionManagement::sessionStarted();
echo SessionManagement::getSession('Foo');
echo SessionManagement::sessionExists('Foo');
} catch(Exception $e) {
echo $e->getMessage();
}
...produces no output...I'm not sure where we're breaking here...any helpful eyes is greatly appreciated...
Unlike other OO languages, like C++, in your class PHP needs to know that the static methods called are from this object. For an instantiated class, that would be through $this, and in your case, static methods, this is done via self:
class SessionManagement {
public static function sessionStarted() {
if(session_id() == '') {
return false;
} else {
return true;
}
}
public static function sessionExists($session) {
if(self::sessionStarted() == false) {
session_start();
}
if(isset($_SESSION[$session])) {
return true;
} else {
return false;
}
}
public static function setSession($session, $value) {
if(self::sessionStarted() != true) {
session_start();
}
$_SESSION[$session] = $value;
if(self::sessionExists($session) == false) {
throw new Exception('Unable to Create Session');
}
}
public static function getSession($session) {
if(isset($_SESSION[$session])) {
return $_SESSION[$session];
} else {
throw new Exception('Session Does Not Exist');
}
}
}
Prepending self:: to all internal calls to the SessionManagement static methods should solve your problem.
How can I check if my object has returned false or not? I have the following class:
class Test {
public function __construct($number) {
if($number != '1') {
return FALSE;
}
}
}
I've tried:
$x = new Test('1');
$x = new Test('2');
But when I var_dump($x), I get the same results. I want to do a:
if(! $x = new Test('1')) {
header("location: xxx...");
}
You cannot return anything from a constructor. If you want the construction of an object to fail, you'll have to throw an Exception.
As deceze said, constructors cannot return a value. You could create a factory method that returns false, like:
class Test
{
public function __construct($number) {
...
}
public function factory($number) {
return ($number != '1') ? false : new self($number);
}
}
$x = Test::factory('1');
if (!$x) {
header('Location: ...');
}
But I would use exceptions instead
class Test
{
public function __construct($number) {
if ($number != '1') {
throw new IllegalArgumentException('Number must be "1"');
}
...
}
}
try {
$x = new Test('1');
} catch (Exception $e) {
header('Location: ...');
}