How to chain method on a newly created object?
In PHP 5.4+, the parser's been modified so you can do something like this
(new Foo())->xyz();
Wrap the instantiation in parenthesis, and chain away.
Prior to PHP 5.4, when you're using the
new Classname();
syntax, you can't chain a method call off the instantiation. It's a limitation of PHP 5.3's syntax. Once an object is instantiated, you can chain away.
One method I've seen used to get around this is a static instantiation method of some kind.
class Foo
{
public function xyz()
{
echo "Called","\n";
return $this;
}
static public function instantiate()
{
return new self();
}
}
$a = Foo::instantiate()->xyz();
By wrapping the call to new in a static method, you can instantiate a class with method call, and you're then free to chain off that.
PHP: Method Chain with new self()?
If I'm not misunderstanding what you're trying to do, if you don't make the second method static, you can return an object and it'll be passed in as $this in the chained call;
class SomeClass {
public $id = 0;
public static function one($id)
{
$obj = new self(); // Create and return new object
$obj->id = $id;
return $obj;
}
public function two()
{
$this->id = 3; // The new object is $this here
return $this;
}
}
$obj = SomeClass::one(5)->two();
Javascript: instantiate an object with chain calling new
To answer your question: yes, you can do this. I have no idea why one might want to do this, but since Javascript is so flexible, it's possible to do most things. Maybe there's an interesting use case.
You can make new
a getter function on the SomeObject
then when you access new
return a newly instantiated object:
var SomeObject = function() {
this.name = "Test"
};
// defined new getter
Object.defineProperty(SomeObject, "new", {
get: function my_new() {
return new SomeObject()
}
});
// add Sometask
SomeObject.prototype.Sometask = function(){
console.log("name:", this.name)
return this // to allow more chaining
}
SomeObject.new.Sometask();
create object chaining using loop
I think looking into functional programming will help you here.
I used a pipe function from the internet link below but you could use lodash/Ramda/underscore or whatever your fav util library is.
the two main concepts I'm using here is currying and piping.
What is 'Currying'? Currying is when you break down a function that takes multiple arguments into a series of functions that take part of the arguments
we are also making use of curring which is returning a function from another function to compose new functions.https://medium.com/@venomnert/pipe-function-in-javascript-8a22097a538e A pipe function takes an n sequence of operations; in which each operation takes an argument; process it; and gives the processed output as an input for the next operation in the sequence. The result of a pipe function is a function that is a bundled up version of the sequence of operations.
what we're doing here is taking an array, creating a new array of functions we want to apply to a value.
So we want to do a load of joins on a db.
join => con => con.innerJoin(join);
is taking a value i.e "table1" and returning a function that takes a db connection which calls the join and returns for the next one.
const joins = toJoin.map(join => con => con.innerJoin(join));
and this creates are array of functions to pass to pipe.
const db = ({
select: function (field) {
console.log('select', field)
return db
},
from: function (table) {
console.log('from', table)
return db;
},
innerJoin: function (join) {
console.log('innerJoin', join)
return db;
}
});
const _pipe = (a, b) => (arg) => b(a(arg));
const pipe = (args) => [].slice.apply(args).reduce(_pipe);
function joinInnerMultiple(table, fields, toJoin) {
const joins = toJoin.map(join => con => con.innerJoin(join));
return pipe(joins)(db.select(fields).from(table));
}
joinInnerMultiple("User", "uuid", ["table1", "table2", "table3", "table4", "table5"])
chain functions directly to newly created object instance in Javascript
This chaining is accomplished by returning this
in your functions :
this.delay = function(per) {
//...
return this;
};
If you want to stick to first line code, then your constructor should be named bar :
var bar = function() {
this.delay = function(per) {
//...
return this;
};
this.start = function() {
...
return this;
};
}
See demonstration (open the console)
How to create chained methods in Java
In this case your removeFrom()
method should return wrapper around ((ArrayList<Object>) entry.getValue())
. And that wrapper has to have method at(int index)
which removes element for given index.
And you also need to think about corner case when your modelsMap
doesn't have entry for a given clazz
.
How to create chaining of objects in js
You can do it using class
style too
class Chainable{
init(num){
this.total = num;
return this;
}
add(num){
this.total += num;
return this;
}
}
using it like so
var c = new Chainable();
c.init(1).add(1);
How does basic object/function chaining work in javascript?
In JavaScript Functions are first class Objects. When you define a function, it is the constructor for that function object. In other words:
var gmap = function() {
this.add = function() {
alert('add');
return this;
}
this.del = function() {
alert('delete');
return this;
}
if (this instanceof gmap) {
return this.gmap;
} else {
return new gmap();
}
}
var test = new gmap();
test.add().del();
By assigning the
new gmap();to the variable test you have now constructed a new object that "inherits" all the properties and methods from the gmap() constructor (class). If you run the snippet above you will see an alert for "add" and "delete".
In your examples above, the "this" refers to the window object, unless you wrap the functions in another function or object.
Chaining is difficult for me to understand at first, at least it was for me, but once I understood it, I realized how powerful of a tool it can be.
Chaining a constructor with an object function call in PHP
The first version does not cause a parse error, it is perfectly valid. The second it is, indeed not possible, but you can easily overcome such a problem with some coding standards.
If every team member creates, for each defined class, a function with the same name as the class, and a signature similar to the signature of the class constructor, then you won't have the second problem. Example:
class Foo
{
public function __construct($param)
{}
public function bar()
{}
}
/**
* @return Foo
*/
function Foo($param)
{
return new Foo($param);
}
Foo()->bar();
Of course, you'll still have problems with library code.
Related Topics
PHP Passing C Struct Data Throught Socket Programming
MySQL Statement Takes More Than Minute to Execute
Post Form and Update Multiple Rows with MySQL
$_Server["Remote_Addr"] Gives Server Ip Rather Than Visitor Ip
Pdo: MySQL Server Has Gone Away
Destroy PHP Session on Closing
How to Prevent PHP Sessions Being Shared Between Different Apache Vhosts
Is Apc Compatible with PHP 5.4 or PHP 5.5
How to Dynamically Write a PHP Object Property Name
Why We Need Curlopt_Ssl_Verifypeer in Windows
The Post Method Is Not Supported for This Route. Supported Methods: Get, Head. Laravel
Using MySQLi from Another Class in PHP
PHP MySQL Update If Exist or Insert If Not
How to Run PHP Files on My Computer
PHP Script Not Working in HTML File
How to Read Cookie/Session Value While Executing PHP5 Script Through Command Prompt