Bruce Gust
asked on
Can you pass variables into a Class in PHP?
I'm working through a tutorial on Node where I've got an MCV architecture going on.
This is the relevant piece of my Controller:
This is the relevant portion of my Model:
What you see works and there's nothing about it that's especially confusing, but I did have a question.
When I saw this syntax, I was able to understand its logic based on my experience with PHP, as far as creating an instance of a class and having a constructor sitting at the top of that class.
All good.
But that I started looking at it a little bit closer and noticed that I was passing a variable into a class.
You don't do that with PHP do you?
I know that's a bizarre question, but when I think of constructors in PHP, I'm thinking of defining some properties and the attaching values to those properties that I can then access throughout my class depending on their visibility.
But do you / can you pass variables into a class in PHP?
There you go! A random question to kick off your Thursday morning...
This is the relevant piece of my Controller:
const Product = require("../models/product");
exports.postAddProduct = (req, res, next) => {
const product = new Product(req.body.title); // right here I'm establishing a new instance of my Product class and I'm passing a variable into that class that's coming from my form
product.save();
res.redirect("/");
};
This is the relevant portion of my Model:
const products = [];
module.exports = class Product {
constructor(title) {
this.title = title;
}
save() {
products.push(this);
}
What you see works and there's nothing about it that's especially confusing, but I did have a question.
When I saw this syntax, I was able to understand its logic based on my experience with PHP, as far as creating an instance of a class and having a constructor sitting at the top of that class.
All good.
But that I started looking at it a little bit closer and noticed that I was passing a variable into a class.
You don't do that with PHP do you?
I know that's a bizarre question, but when I think of constructors in PHP, I'm thinking of defining some properties and the attaching values to those properties that I can then access throughout my class depending on their visibility.
But do you / can you pass variables into a class in PHP?
There you go! A random question to kick off your Thursday morning...
ASKER
OK, Gonzo! I get that, but could you do something like this:
$MC1 = new MyClass($color, $fruit);
$MC1->DisplayStuff();
$MC1 = new MyClass($color, $fruit);
$MC1->DisplayStuff();
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
That was my question, gentlemen, and you answered it.
Thanks!
Thanks!
You are welcome Bruce.
Open in new window
Output:
Open in new window