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

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.

Related

Multiple Method Access Inside Class PHP [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 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.

Is it bad practice to call a static method via an object? [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 4 years ago.
Improve this question
I found that calling the static method via object can be very convenient in some use case.
I'm wondering if this is is considered as a bad practice?
or if this feature will be removed in the future version of PHP?
class Foo
{
public static function bar ()
{
echo 'hi';
}
}
class SubFoo extends Foo
{
public static function bar ()
{
echo 'hi subfoo';
}
}
// The normal way to call a static method.
Foo::bar(); // => "hi"
// Call the static method via instance.
$foo = new Foo;
$foo::bar(); // => "hi"
// Here is the use case I found calling static method via instance is convenient.
function callbar(Foo $foo)
{
// The type-hinting `Foo` can be any subclass of `Foo`
// so I have to figure out the class name of `$foo` by calling `get_class`.
$className = get_class($foo);
$className::bar();
// Instead of the above, I can just do `$foo::bar();`
}
callbar(new SubFoo); // => "hi subfoo"
As a general rule, using static methods is bad practice because:
In fact, static methods or static variables are global variables
static code makes can cause many troubles in testing
static code makes high cohesion between parts of code
static code makes hidden dependencies between parts of code
But, there are cases when using static code is justified. For example:
Methods refer to a class and don't refer to objects
Helpers or Util classes which don't have their states

What are best practices for using utility functions within PHP classes? [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
I'm coming into object-oriented PHP from a more functional Javascript background, so I'm fairly new to both PHP and OOP.
What I'm trying to do is make a class that that is passed the contents of a text file, divides it up into manageable pieces, and then loops over those pieces (steps), and handles them accordingly, sometimes making HTTP requests, sometimes saving chunks of info into a $fileVariables array. Here's a basic outline of what I have:
class Script {
public $file, $client, $fileVariables;
function __construct($file) {
$this->file = $file;
$this->client = new \GuzzleHttp\Client();
$this->fileVariables = array();
}
public function parseAndRun() {
$client = $this->client;
$file = $this->file;
// this is the function that performs the bulk of the class's
// work. It relies on some utility functions that are defined
// after, and are utilized within this function like this:
$steps = $this->divideFileIntoSteps($file);
// or like this:
$this->setVariable($index, $value);
}
public function divideFileIntoSteps($file) {
// return array of file divided into steps
}
public function setVariable($index, $value) {
// push $index => $value into $fileVariables array
}
}
I think it's possible that I'm trying to do something that would be totally okay in functional Javascript, but just feels sloppy in object-oriented PHP. Also, when I run PHPUnit tests on this, I get an error that's something like Serialization of 'Closure' is not allowed, which I think from doing some googling on the error might have something to do with how I'm doing this. Also, the fact that I have to use $this-> over and over again on commonly used functions makes me feel like I'm doing something wrong. It just gives me that bad code feeling.
Is there a better way to do this, bearing in mind that a lot of the functionality has to do with getting and setting items in the $fileVariables array?
Your code is basically correct.
You don't need $file = $this->file;
$this prefix is standard for accessing member functions and variables in PHP.
Your function could look like this:
public function parseAndRun() {
$steps = $this->divideFileIntoSteps($this->file);
// or like this:
$this->setVariable($index, $value);
}
Another best practice is to declare private all methods that you don'n need to access from outside the class. Member variables should all be private and you should have accessor functions for them.

A few PHP questions (echo / OO PHP) [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
I learning a bit of OO PHP but the docs I came across showed a couple of methods of the following examples. I am confused as to why both work, and which should be used exclusively.
I know that #1 is not OOP but I was still curious about the second method of echo, and if it should be used or not.
Both of the echo's below print "Lansana", but one initializes $name before the echo whereas the other initializes it after (or during) the echo.
<?php
$name = "Lansana";
echo $name;
echo $name = "Lansana";
?>
Notice how there is a public property $name with no value in the first example, and no public property in the second, yet both still work the same.
class Pets
{
public $name;
public function __construct($name) {
$this->name = $name;
}
}
$dog = new Pets("Buddy");
echo $dog->name;
class Pets
{
public function __construct($name) {
$this->name = $name;
}
}
$dog = new Pets("Buddy");
echo $dog->name;
What is the preferred method in #1 and #2, and why? I don't know why the docs showed the first class method because I don't see the need for a public property there, but then again what do I know.
Thought I should give a little more context to what I outlined in the comments above.
For the First example try not to mix assignment and output in the same statement. Although it is syntactically correct it doesn't immediately indicate the intent of the statement.
For the second example as I stated in the comments explicitly defining properties is always preferable. The advantages are:
Most IDE's will auto-complete defined properties for you minimizing the risk of mistyping a property.
It clearly indicates to someone reading the code what properties are available on the object.
It allows for you to set the visibility of the property so you can control more how your class is used which promotes encapsulation.
One of the most common bugs that you see with OO PHP is when you silently create a property for example something like:
class A {
public function setUserId($id){
$this->userId = $id;
}
public function getUserId(){
return $this->userid;
}
}
The intent is clear here but you have to be paying pretty close attention to the fact that the referenced properties are cased differently. If becomes much harder if you throw in another 50 lines of code and the two property references aren't on the screen at the same time.
On of the uses for PHP's magic __get and __set method are to help eliminate this problem earlier in development. Example:
class A {
public $foo;
public $bar;
public function __set($prop, $val){
throw new Exception ($prop." does not exist on this object");
}
public function __get($prop){
throw new Exception ($prop." does not exist on this object");
}
}
This makes it where if you attempt to access an undefined property the class will throw an exception letting you know exactly what happened and where.
I think #1 is just a shortcut. #2 is because of overloading, where class variables are created dynamically.
http://www.php.net/manual/en/language.oop5.overloading.php
As for preferred methods, with #1 'echo $name = 'Something'` more of a short cut than a different method. The end outcome is the same in either case.
With #2, dynamically created variables are not usually a good idea as it can generate some unexpected results but they do have their place. Check the link above for some example of code using overloading. The first method is favored.
1
echo $name = "Lansana";
PHP interprets it as
echo ($name = "Lansana");
echo sort of works like a function, because of that php interprets everything on the right side of the echo before sending it to standard out.
2
The first one is definitely the best way. Because PHP is a dynamic language (as opposed to a static language like C# or Java) it allows one to create and set variables without declaring them first. It is the best to always declare class variables--it makes the code easier to read and maintain.

What's the best way to store class variables in PHP? [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
I currently have my PHP class variables set up like this:
class someThing {
private $cat;
private $dog;
private $mouse;
private $hamster;
private $zebra;
private $lion;
//getters, setters and other methods
}
But I've also seen people using a single array to store all the variables:
class someThing {
private $data = array();
//getters, setters and other methods
}
Which do you use, and why? What are the advantages and disadvantages of each?
Generally, the first is better for reasons other people have stated here already.
However, if you need to store data on a class privately, but the footprint of data members is unknown, you'll often see your 2nd example combined with __get() __set() hooks to hide that they're being stored privately.
class someThing {
private $data = array();
public function __get( $property )
{
if ( isset( $this->data[$property] ) )
{
return $this->data[$property];
}
return null;
}
public function __set( $property, $value )
{
$this->data[$property] = $value;
}
}
Then, objects of this class can be used like an instance of stdClass, only none of the members you set are actually public
$o = new someThing()
$o->cow = 'moo';
$o->dog = 'woof';
// etc
This technique has its uses, but be aware that __get() and __set() are on the order of 10-12 times slower than setting public properties directly.
If you're using private $data; you've just got an impenetrable blob of data there... Explicitly stating them will make your life much easier if you're figuring out how a class works.
Another consideration is if you use an IDE with autocomplete - that's not going to work with the 2nd method.
If code is repetitive, arrays and (foreach) loops neaten things. You need to decide if the "animal" concept in your code is repetitive or not, or if the code needs to dig in to the uniqueness of each member.
If I have to repeat myself more than once, I loop.
Use the first method when you know you need that variable.
Use the second method (an array collection of variables) when you have dynamic variable needs.
You can combine these 2 methods, so some variables are hardcoded into your class, while others are dynamic. The hardcoded variables will have preference compared with magic methods.
I prefer the first method, for a few reasons:
In a good IDE, the class properties show up, even if private/protected
It's easier to see what has already been defined, reducing the chance you store the same information twice.
If the proverbial bus hits you on the way home, it's a lot simpler for another developer to come in and read your code.
And while it doesn't apply to private var, it does to protected vars, in classes that extend this class, you really should try to avoid the second method for pure readability.
Also, as a side note, I almost always choose protected over private unless I have a very specific reason to make it private.
The only time I'd probably use the second method was if I was storing a collection of many of one kind of thing.

Categories