Multiple Method Access Inside Class PHP [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm new in PHP OOP and curious about method. How to make method inside method (I dont know what its name)?
For example, I can access like this
<?php
$myClass = new CarClass;
$myClass->createNew->bodySection->setColor("red");
Just like Codeigniter for calling a Models or Library using this.
<?php
$this->myLibrary->getData()
It's different from method chaining where between method call there is no parameter, its like javascript.
Can I achieve that? Or any alternative?
Thank you

Given the code,
$myClass = new myCar;
$myClass->createNew->bodySection->setColor("red");
we can make the following statements:
myCar has a property named “createNew”.
createNew holds some unknown object
The unknown object has a property called bodySection
The property named bodySection contains an unknown object that has a method named setColor()
Clear as mud?
There are several ways this could be illustrated; here’s one:
class myCar {
public createNew;
public function __construct() {
$this->createNew = new Foo;
}
}
class Foo {
public bodySection;
public function __construct() {
$this->bodySection = new Bar;
}
}
class Bar {
public function setColor($color) {
echo "Color is $color";
}
}
$myClass = new MyClass;
$myClass->createNow->bodySection->setColor('red');
// output: Color is red
The first problem here is that “createNow” doesn’t make sense as a property; it’s an action, not something that a myCar would own or do.
Likewise, a bodySection would probably have a color as a property, to be set with its own setter method, not some external object.
Bottom line, making long chains of pointers is not something to seek after; rather, they’re probably better kept as short as possible. Otherwise your object probably knows too much about to many things.

Related

Why use Dependency Injection in this example? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Consider the following code:
class CategoryController
{
private $model;
public function __construct()
{
$this->model = new CategoryModel();
}
}
You will see that Controller depends on the Model. I've heard that doing so is not desirable and Model should be injected instead.
I question why. In my case, I build CategoryModel specifically for CategoryController and I don't see a problem leaving it like this inside the class. I mean, I can't inject SomeOtherModel that's not compatible in there anyway... or can I?
Using Dependency Injection to instead inject it into the Controller seems like waste of code.
Hence, is there any reason to use DI here?
answer
Actually in that example, the big question is what is that for?! No methods just an object holder without any way to get it!?
Yea I know, it's just an example, but thats the problem, in that example you don't need DI, actually you not even need the class at all!
Has #Mark Baker said, without the DI/IoC you can't easily test, since it's tightly cupelled. If you take sometime to read about testing and for this case also Mockery
extra
Using Dependency Injection to instead inject it into the Controller seems like waste of code.
When in cases where you don't have something that does the DI for you, it's easy to allow the objects to pass from constructor or make the default ones, in your example would be something like:
use CategoryModelInterface;
class CategoryController
{
private $model;
public function __construct(CategoryModelInterface $categoty = null)
{
$this->model = $category
? $category
: new CategoryModel();
}
}
This way you don't lose much time, and when/if/maybe you'll do some testing, or change the model completely for another, it's actually possible to do it.
I don't think you'll need DI here. However Mark Baker's comment about testing is valid. But you can get around that by using a getter method for the model. That method can then be mocked in tests:
class CategoryController
{
private $model;
public function __construct()
{
...
}
public function getModel() {
if(!$this->model) {
$this->model = new CategoryModel();
}
return $this->model;
}
}

PHP Classes:: Why declare as a new? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm very new to php classes and I was wonder why do I need to declare it to a variable and set it as NEW?
Here is an example :
class myFirstClass {
function Version(){
return 'Version 1';
}
function Info(){
return 'This class is doing nothing';
}
}
$hola = new myFirstClass;
echo $hola->Version();
Why this won't work WITHOUT declare it to a variable and set it to NEW ?
In other words... Without this line :
$hola = new myFirstClass;
I'm so used to functions so it looks weird to me...
This is a basic principle of Object Oriented Programming (OOP). Let's use a library system for example. If you want to get the name of a book, you cannot just say "give me the name of the book", you have to know what book (by id, author, whatever).
In functions, you can write one that looks like this:
function get_book($id){ // code }
In OOP it doesn't really work that way. You have a class book that keeps a name. But that name is only for that given book.
class Book {
var $name;
public __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
In order to call the getName() function we need to have a book. This is what new does.
$book = new Book("my title");
Now if we use the getName() function on $book we'll get the title.
$book->getName(); // returns "my title"
Hope that helps.
You are right! It is not necessary to use the new operator:
class myFirstClass {
static function Version(){// static keyword
return 'Version 1';
}
function Info(){
return 'This class is doing nothing';
}
}
echo myFirstClass::Version();// direct call
To create an instance of a class, the new keyword must be used. An object will always be created unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation (and in some cases this is a requirement).
If a string containing the name of a class is used with new, a new instance of that class will be created. If the class is in a namespace, its fully qualified name must be used when doing this.
The Basics
http://php.net/manual/en/language.oop5.basic.php
Classes and Objects
http://php.net/manual/en/language.oop5.php
This line:
$hola = new myFirstClass;
Is saying: create a new object called $hola, then put a new instance of myFirstClass into $hola. Now $hola is literally a object containing a new instance of myFirstClass.

Object oriented php object,class and methods [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
$Clint_ip=$this->request->clintIp();
May I get a clear concept about this line?In here I know $clint_ip is a variable,but what is the next three?which one is an object?
which one is a method?
which one is a class?
I just need to understand this line.In several project I have seen this types of line.In this line which one called object?If you want You can give another example.In here $this is an object?or class?or method?
Yes $Clint_ip is an variable,
Like other object oriented based programming languages $this is the this of a class consisting it. (For more about this When to use self over $this?)
request looks like an object of another class
and clintIp() is the public method of the class of the request object
The code you provided appears to be from inside of a class.
A class is denoted like this:
class Example {
private $foo;
public $bar;
public function __construct() {
}
public function method() {
}
private function other() {
}
}
When you create an object of this class, you can use the format:
$example = new Example();
This calls the constructor __construct().
Once you have created ("instantiated") this object, you can use the -> to call the properties of the object.
So, I can say
$example->bar = "Foo";
which sets this property to a string.
Your Code
In your code, the property "request" is itself an object (an instance of a class).
$Clint_ip=$this->request->clintIp();
Here is an example of the code this could be using
class Example {
public $request;
public function __construct($request) {
$this->request = $request;
}
}
class Request {
public function clintIp() {
//return something
}
}
And then some context:
$request = new Request;
$example = new Example($request);
$clint_ip = $example->request->clintIp();
So here, $clint_ip is the variable. $example and $request are objects (instances of classes), and clintIp() is a method of the request object.
Now, about "$this". This indicates that it is within the object "Example":
Imagine the class Example now has a method
public function test() {
return $this->request->clintIp();
}
$this means that it is inside of an instance of an object. In static context, use "self::", as mentioned in one of the other answers.
You are inside object which has request property. Request property contains object with method clintIp() which return client ip.

PHP Methods and Class Design [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
Which design concept is better in PHP; passing variable to the function myFunct() or not passing the variable?
<?php
class A{
public $myvar=1;
public function myFunc($myvar){
$this->myvar=$myvar+1;
}
}
$myA=new A();
$myA->myFunc($myA->myvar);
// OR THIS ONE
class A{
public $myvar=1;
public function myFunc(){
$this->myvar=$this->myvar+1;
}
}
$myA=new A();
$myA->myFunc();
?>
Here is maybe a better example of what I am trying to understand:
class PhotosBasicClasses{
protected $srcImage;
protected $fileImageTypeFlag;
public function createThumb($srcImage,$fileImageTypeFlag){
$this->srcImage=$srcImage;
$this->fileImageTypeFlag=$fileImageTypeFlag;
$resourceNewImage=$this->imageCreateFromFormat($srcImage,$fileImageTypeFlag); //with or without the parameters is better?!
}
protected function imageCreateFromFormat($srcImage,$fileImageTypeFlag){
switch($fileImageTypeFlag){ //this is my problem: would be better to use the class variable or the internal variable($fileImageTypeFlag or $this->fileImageTypeFlag )
case 'jpeg': return imagecreatefromjpeg($srcImage);break;
case 'png': return imagecreatefrompng($srcImage);break;
case 'gif': return imagecreatefromgif($srcImage);break;
default: return "error source file format";
}
}
Generally keep at class scope variables describing your class and usually required by most of your "important"(methods tha also describe what the class can do or has) methods.
At first glance, in your case the method imageCreateFromFormat($srcImage,$fileImageTypeFlag) looks fine and self contained . But the method createThumb if all it does is what you posted then remove it along with the two class variables and rename the other method to createThumb.
If it is unfinished and after calling the method imageCreateFromFormat is going to crop the image and create a thumbnail, then there is no reason to have class scope variables you can remove them unless you plan to rename the class and add a bunch of methods that use these two variables.
Finally, care must be taken with class names, it is not good practice to use plural and the word class.
Neither of this examples is good. If you want to have object variable it's better to make it private.
By the way, your examples is doing differnt tasks, becouse first gets variable through function params increments it by one and save to object variable and second example only increments object variable by one.
Instead of "$this->myvar = $this->myvar+1;" you can use "$this->myvar++;"

PHP5. Two ways of declaring an array as a class member [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
When declaring an array as a class member, which way should it be done?
class Test1 {
private $paths = array();
public function __construct() {
// some code here
}
}
or
class Test2 {
private $paths;
public function __construct() {
$this->paths = array();
// some code here
}
}
Which one is better in terms of good practices and performance? What would you recommend?
I'd suggest doing this when declaring a class variable. A constructor can be overriden in extending classes, which might result in E_NOTICEs or even E_WARNINGs if any of your functions depend on this variable being an array (even an empty one)
If you are going to populate your array dynamically during initialization, do it in the constructor. If it contains fixed values, do it in the property declaration.
Trying to populate an array dynamically (e.g. by using the return value of a certain function or method) within the declaration results in a parse error:
// Function call is not valid here
private $paths = get_paths();
Performance is not a real concern here as each has its own use case.
In general, because I write mostly in other languages besides PHP, I like to declare my instance variables outside of the constructor. This let's me look at the top of a class and get an idea for all properties and their access modifiers without having to read the code.
For example, I really don't like methods like this
// ...
// whole bunch of code
// ...
public function initialize() {
$this->foo = array();
// some other code to add some stuff to foo
}
Now, if I just look at the class, I can't be sure there is a variable foo even available. If there is, I don't know if I have access to it from anywhere outside the instance.
If instead I have:
public $foo = array();
at the top of my class, I know that foo is an instance property, and that I can access it from elsewhere.
There are no performance implications. Stop obsessing over things that don't matter - concentrate on performance problems that ARE there: measure first, optimize only the top offenders.

Categories