Call function directly after constructor: new Object()->callFunction() - php

As you might have seen in the title, my programming background is Java. In Java you can do stuff like this
new Object().callSomeMethod();
without assigning the created Object to a variable, very useful and clear coding if you only need this Object once.
Now in PHP i try to do the same
new Object()->callSomeMethod();
but here i get a 'Parse error: syntax error, unexpected '->' (T_OBJECT_OPERATOR)'.
Is there a way to do this in PHP ?

(new Object())->callSomeMethod();
will work in PHP 5.4+
EDIT
It is a new feature added on PHP 5.4:
Class member access on instantiation has been added, e.g. (new Foo)->bar().
EDIT2
The PHP feature RFC proposes two sets of syntax(with & without brackets), both of them are implemented in the RFC, but only one has been shipped. I couldn't find links explaining the decision.
Let's take a look at the bracketless syntax examples in the RFC:
new foo->bar() should be read as (new foo)->bar()
new $foo()->bar should be read as (new $foo())->bar
new $bar->y()->x should be read as (new ($bar->y)())->x
I think bracketless syntax is not shipped because its proposed parsing precedence is not very intuitive(hard to follow by eyes) as shown in the 3rd example.

Related

How to add nameddest to existing PDF

I tried to use PDF_add_nameddest to add nameddest but I don't know exactly how to use it or is it possible. My codes are:
$pdf = pdf_new();
pdf_open_pdi_document($pdf, 'test.pdf', "");
pdf_add_nameddest( $pdf , 'testdestination', 'bottom' );
My reference on the third parameter 'bottom' is from here. But did I used it the right way? I don't understand clearly.
The error on that is:
PDFlib exception occurred in starter_basic sample: [2100]
PDF_add_nameddest: Function must not be called in 'object' scope
Is my code missing something or is it completely wrong?
Or even better, do you know something I should use to do this adding nameddest??
you get this scope error, because you haven't yet open an new output document (so you are still in object scope). As you might have seen in the PDFlib API reference, for the function "add_nameddest()", the scope for this API call is:
Scope: any except object
So, when you move the call after begin_document() the destination will be added to the new output document.
Please check also PDFlib 9.1 API Reference, chapter 12.5 "Named Destinations" (or related to your used version) for more details on this function.

Yet another PHP Parse error: syntax error, unexpected 'use' (T_USE)

I lost my evening on this and I feel like I need somebody other to check this, I'm probably completely blind.
define('FACEBOOK_SDK_V4_SRC_DIR', '/var/www/rateanything/facebook-sdk/src/Facebook');
require('/var/www/rateanything/facebook-sdk/autoload.php');
use Facebook;
FacebookSession::setDefaultApplication('my_app_id', 'my_app_secret');
$session = new FacebookSession($fbtoken);
$request = new FacebookRequest($session,'GET','/me?fields=email,name,gender');
Why this is not duplicate: Because that question has not this error. I'm getting this parse error.
I'm using PHP 5.4.
Is that code wrapped inside a function? The use keyword can only be applied on the outermost scope of your file.
Basically, move use Facebook; to the top of the file.
Alternatively, you could probably reference the namespace in which FacebookSession and FacebookRequest is defined. Like so:
define('FACEBOOK_SDK_V4_SRC_DIR', '/var/www/rateanything/facebook-sdk/src/Facebook');
require('/var/www/rateanything/facebook-sdk/autoload.php');
Facebook\FacebookSession::setDefaultApplication('my_app_id', 'my_app_secret');
$session = new Facebook\FacebookSession($fbtoken);
$request = new Facebook\FacebookRequest($session,'GET','/me?fields=email,name,gender');
So based on the error this is the problem line
use Facebook;
Without knowing what's in that include it's hard to say, but it doesn't look like you're aliasing anything. In fact, if you're autoloading (which seems like a safe bet) you shouldn't use an alias like that.
Normally you'd use it like this
include 'facebook.php';
use Facebook;
\Facebook\SomeClass::staticFunction($var);
$class = new \Facebook\OtherClass();
Check out the manual for more details and examples on how to use use

A complex soap call using PHP

I've worked on this for about 4 hours and I am real close but just missing the mark – here is what xml needs to look like
<ws:Answer QuestionID="Q_CAM_ID" ws:Datatype="string">
<ws:Value>6838</ws:Value>
</ws:Answer>
Here is what I get
<ns1:Answer QuestionID="Q_CAM_ID">
<ns1:Value>6838</ns1:Value>
</ns1:Answer>
Using
$A1 = new StdClass();
$A1->QuestionID = 'Q_CAM_ID';
$A1->Value =6838;
No matter what I try I can’t get “ws:Datatype="string"” to appear. I believe the answer is the below or real similar
$A1 = new StdClass();
$A1->QuestionID = new StdClass();
$A1->QuestionID->QuestionID ='Q_CAM_ID';
$A1->QuestionID->DataType ='string';
$A1->Value =6838;
But what I keep getting is this error
Catchable fatal error Object of class stdClass could not be converted to string when the soap call is done. If anyone has a clue I would be most appreciative
The simliest way to do it is to use a WSDL to php generator as you'll only deal with PHP object that matches the requires types. Moreover, if you a good WSDL to php generator, you'll have PHP classes that are named as the elements.
You could use https://www.wsdltophp.com or https://github.com/mikaelcom/WsdlToPhp.
Maybe I'm missing something but if you need that XML why not just make it as a String, and then convert it to what you are trying to do? If you are not using a WSDL or SimpleXML, I would just do the following.
$xml =
'
<ws:Answer QuestionID="Q_CAM_ID" ws:Datatype="string">
<ws:Value>6838</ws:Value>
</ws:Answer>
';

PHP subclass not calling its parents construct

I have some classes set up as this, where -> means 'extends':
DBObject -> Article -> Activity
DBObject contains a generic __construct to easily load my objects from the database (hence DataBaseObject).
Article overrides this __construct, for some specialized constructor behaviour.
Activity does not implement any __construct, as it can be handled by its superclass' __construct (Article::__construct).
However, for some reason, if I call
$activity = new Activity($args);
It ends up in DBObject::__construct, and passes Article's one all together. I always thought that calls on a subclass were supposed to travel up the subclass line one class at a time. Am I mistaken in thinking that?
EDIT: Here's a code snippet: http://pastebin.com/SXpSNVMm. I removed all non-necessary code. I'm calling it like this:
$userId = 60;
$title = "TestTitle";
$contents = "Lorem ipsum dolor sit amet";
$date = 1356173771;
echo "creating new activity\n";
$a = new Activity($userId, $title, $contents, $date);
Placing echo's in the constructors revealed that Article::__construct() was not used and it went right to DBObject::__construct().
Edit 2: This is a version that should be working properly: http://ideone.com/VJzdI3 . I'm using PHPUnit for testing. This is the output if i run with PHPUnit:
creating new activity
DBObject constructed called
QUERY: 60 ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '60' at line 1
The latter means it's trying to initialize it using meekrodb; That should only happen if i call new on a subclass of DBObject with something other than null or an array. However, since Article should override __construct, that one should be called first.
Your understanding is correct: with the setup you describe creating a new Activity would definitely "defer" to Article::__construct. If it does not then your description and the actual code have to differ somewhere. PHP has its more than fair share of bugs, but this is a very simple scenario to attribute the surprising behavior to buggy code.
If you still think there is nothing wrong with the code, please post a working sample on an online codepad like htpp://ideone.com that exhibits the issue.

Why can't I declare an instance variable as an array of objects in PHP?

I am writing a customer management system in PHP, for use offline (i.e. on the clients computer). I have considered using Java or C# but have come to the conclusion that it is easier to let the browser do all the layout for me, and just have the company install wamp on their computers.
Through this interface they will also be able to manage Agents (i.e. salesmen that go round their area getting orders for the company, in case any doesn't know). This is the section I will use in this post to demonstrate the problem I am having.
Basically I have 4 classes - AgentPages, AgentList, AgentDetails and AgentForm. AgentForm will have two modes - edit and new. AgentPages has a function called getPages, which returns an array of instances of the other 3 classes. However it does not like the "new" keyword.
My code is as follows (for the AgentPages class only):
<?php
require_once("AgentList.php");
require_once("AgentDetails.php");
require_once("AgentForm.php");
class AgentPages {
public function __construct() {
echo "Constructed";
}
private $pages = array("List" => new AgentList(), "Details" => new AgentDetails(), "Form" => new AgentForm());
function getPages() {
return $this->pages;
}
}
?>
I am using the netbeans 6.9 IDE with PHP enabled, and (as you can probably guess) I have wamp server installed. Under PHP version 5.3 the netbeans debugger is telling me that "Parse error: parse error in C:\wamp\www\CustomerApp_v2\Agents\AgentPages.php on line 20". Under 5.2.11 it says something about unexpected T_NEW on that line. I have cut out a large comment on this, before line 20, but I can tell you that line 20 is the declaration of $pages. I have an empty constructor for each class at the moment.
I have also tried the following line instead of line 20:
$AgentList = new AgentList();
This doesnt work either - I get the same error. According to all the tutorials I have looked at there is nothing wrong with my code - I am probably just overlooking something obvious though.
Does anyone have any idea what I am doing wrong? I have done lots of PHP object oriented stuff before now, but the last time I touched it was 2 years ago.
Thanks in advance.
Regards,
Richard
The problem is that you're trying to initialize an instance variable in a declaration with an expression (a call to new is an expression). That doesn't work. Put the assignment in the constructor and it will work.
Like this:
class AgentPages {
public function __construct() {
$this->pages = array("List" => new AgentList(), "Details" => new AgentDetails(), "Form" => new AgentForm());
echo "Constructed";
}
private $pages;
}

Categories