r/PHPhelp • • Oct 16 '21

Solved when you would u use a static function?

9 Upvotes

im coming from python and very new to php

consider this:

    class normalUser
    {
        const rank = NORMAL;
        private $rank = NORMAL;

        static function static_function()
        {
            return self::rank;
        }

        function just_function()
        {
            return $this->rank;
        }
    }

this is my understanding:

	$new_user = new normalUser;
	echo $new_user->just_function();		#call class method in object context
	echo normalUser::static_function();		#without initializing an object of class

this is weird. i guess static methods can be used to grab a class's constant property without instantiating the class or something? i guess a slight performance optimization?

static methods can only access its class's constant properties so if thats not what the implemented static method does that means the method has nothing to do with the class really, in which case i would be better off writing a function that does the same thing outside the class scope?

what r sum practical examples where this kind of weird technique is used?


r/PHPhelp • • Aug 25 '21

How do I find out what I don't know?

9 Upvotes

All of my php knowledge has been self taught over the years and I've just kind of stumbled upon information randomly and other times I learn out of some specific need, which leads me to outdated SO answers that I tweak to fit my needs to what I believe to be more updated and better code.

However...

I've noticed over the past few months here that there's random things I either didn't know I didn't know, or I have learned to be outdated and should be burned with fire. Example 1, I have no idea what this variable leading with a period $.var thing is. Example 2, apparently setting a variable conditionally is a no-no? $a = ( $b > $c ) ? $x : $y;

Where do I go to find my I unknown unknowns?


r/PHPhelp • • May 20 '21

Learn PHP

9 Upvotes

I want to learn advanced PHP, give some suggestions about books, topics, and other necessary things...


r/PHPhelp • • Apr 28 '21

Is there a way to test a function with static variables? (PHPUnit)

9 Upvotes

Ιs there a way to test a function containing static variables using PHPUnit?

For example,

class MyClass {
  public function my_method() {
    static $already_invoked = false;
    
    if ($already_invoked) {
      return;
    }

    echo 'Hello world';

    $already_invoked = true;
  }
}

my_method() will print Hello world exactly one time, no matter how many times it's called.

$instance = new MyClass();
$instance->my_method();
$instance->my_method();

outputs:

Hello world

Having just one test

<?php
class MyMethodTest extends \PHPUnit\Framework\TestCase {
    public function test_should_print_hello_world_exactly_one_time() {
        $instance = new MyClass();
        $instance->my_method();
        $instance->my_method();

        $this->expectOutputString('Hello world');
    }
}

passes:

MyMethod
 ✔ Should print hello world exactly one time

However, adding another test

<?php
class MyMethodTest extends \PHPUnit\Framework\TestCase {
    public function test_should_print_hello_world() {
        (new MyClass())->my_method();

        $this->expectOutputString('Hello world');
    }

    public function test_should_print_hello_world_exactly_one_time() {
        $instance = new MyClass();
        $instance->my_method();
        $instance->my_method();

        $this->expectOutputString('Hello world');
    }
}

causes the previously passing test to fail, because of the static variable:

MyMethod
 ✔ Should print hello world
 ✘ Should print hello world exactly one time
   │
   │ Failed asserting that two strings are equal.
   │ --- Expected
   │ +++ Actual
   │ @@ @@
   │ -'Hello world'
   │ +''
   │

Now, I know I could use a static property instead:

class MyClass {
    private static bool $already_invoked = false;

    public function my_method() {
        if (self::$already_invoked) {
            return;
        }

        echo 'Hello world';

        self::$already_invoked = true;
    }
}

That way, I could use a reflection property to reset its value immediately after each test, like this:

class MyMethodTest extends \PHPUnit\Framework\TestCase {
    // ...

    public function tearDown() {
        $ref = new ReflectionProperty('MyClass', 'already_invoked');
        $ref->setAccessible(true);
        $ref->setValue(null, false);
    }
}

And then, both tests pass:

MyMethod
 ✔ Should print hello world
 ✔ Should print hello world exactly one time

In my case, though, I'm dealing with legacy code and I'd like to write some unit tests before refactoring it.

I've also tried to run each test in isolation (although that's not ideal since it'd probably end up being considerably slower) using the @runInSeparateProcess method annotation, but that seems to be failing because the process isolation feature requires serialization:

PHP Fatal error:  Uncaught Exception: Serialization of 'ReflectionClass' is not allowed in phar:///usr/local/bin/phpunit/phpunit/Util/GlobalState.php:151

Is there a way to test a function containing static variables?


r/PHPhelp • • Feb 11 '21

Can someone code review my PHP project?

9 Upvotes

Introduction

I've been lucky enough to get my first job as a junior PHP developer. I am concerned I'm not good enough because I am only 16. I would like to brush up on my coding and get as much constructive criticism as I can.

What is it?

This is a SQL query builder, built for MySQL that provides a fluent, chaining API to build a query, and allows you to output the raw SQL. How can I improve the quality of it, as well as any features you can think of that I can try to practice.

API:

https://gist.github.com/WholePatient9125/bb51995a4e9d7fef8fab9184f663698b

Gist class (QueryBuilder): https://gist.github.com/WholePatient9125/cd8b275882836d49e30e1df55ffdebb7

Many, many thanks in advance to everyone who helps.

I know the support for multiple where clauses is weak, and maybe I forgot to add some options and be more flexible, but this was to the best of my basic SQL knowledge, I'm open to challenges.


r/PHPhelp • • Jan 18 '21

what kind of projects are better with php than with other web programming languages?

9 Upvotes

r/PHPhelp • • Dec 08 '20

Solved Which coding conventions do you follow, if any?

9 Upvotes

I recently had a debate with a colleague about coding conventions in PHP code. My PHP skills are rusty and I really don't know the best practices. Do you work in an organization that has multiple people maintaining a PHP code base? If so, I'd be grateful for insights.

  • Do you follow a coding convention? If yes, which one? Is https://www.php-fig.org/psr/psr-12/ a thing?

  • Do you specify things like indentation style? To which extent?

  • Do you allow curly braces, "alternative" control structures or both?

  • Is it OK in your organization to use many different coding styles? If yes, how do you decide which file uses which style? Can styles be mixed in a single file?

  • Do you use an automatic formatting tool? Which one?

I'm trying to find out a general sentiment. Do you see coding standards as a hindrance to work or as a way to help the team to work? Is there a point after which a standard is too strict?

Thanks in advance.


r/PHPhelp • • Nov 26 '20

Good resource for learning best practices on architecture/scalability?

9 Upvotes

My PHP skills have gotten really good over the past couple years (IMO), but I sometimes find myself building methods and classes that don't scale as well as I'd like, though I'm getting better at it.

I've usually don't have a dev above me to teach me best practices, and I'm guessing there's a good resource for learning.

Anyone recommend something that would help?


r/PHPhelp • • Oct 09 '20

Getting extremely frustrated with debugging situation

9 Upvotes

I keep having to post questions here because I keep getting stuck on my homework. The way our professor wants us to do our work, we're supposed to write our HTML + PHP in Notepad++, upload it to the class server, test it, re-write it, re-upload it, test it again, and so on, until it works. The problem is that there's no error messages more helpful than HTTP error 500, even with the error reporting code y'all gave me the other day. I still only get HTTP error 500 messages. Is there some other IDE that I can use that will spot syntax issues and other stuff before I upload it? I'm really sick of getting stuck and having to ask for help. Thanks.

PS. I know I sound upset, but I'm not mad at you guys, I'm mad at the situation.


r/PHPhelp • • Sep 08 '20

How can I get this string replace to work on a copied and pasted apostrophe?

9 Upvotes

Hello-

I am trying to replace this, in a string: ’

$quote = str_replace("’", "'", $row["quote"]);

The above is what I tried but it does not work. My initial problem is that I copied and pasted quotes from Google Docs in my database. When these quotes are displayed on page, the apostrophe is displayed as a black triangle with a question mark, showing that the character in question cannot be interpreted right. I tried doing a replace in the database table, but that does not work, so now I am trying to replace the apostrophe before the browser attempts to display it. Thus this function above.

SOLUTION:

//detect encoding coming from DB

$enc = mb_detect_encoding($row["quote"]);

// change encoding to UTF-8

$quote = iconv($enc, "UTF-8", $row["quote"]);


r/PHPhelp • • Jun 15 '20

Careers Question: Has anyone switched from .NET to PHP and then back to .NET?

9 Upvotes

If this question doesn't belong here, please let me know and I'll remove it.

I'm in a bit of a minor crossroads moment in my professional career. I started out as a .NET developer for 2.5 years and then fell into a PHP/.NET position at my current job (2 years and counting). I'm looking to switch jobs soon and I've always assumed that I would switch back to .NET, until I saw a job position (tentative current opening) in PHP that's making me second guess.

I'm in the middle of a "do I stay in programming or switch careers all together" moment, but I'm not ready to throw in the towel yet. I wanted to ask if anyone has had the switch like in the title OR has switched long-term to PHP? If the latter, what's the industry been like for you? How has it changed in the last several years (or in the duration you were a PHP dev)? How's the job growth in this part of the market? I know what to expect with .NET but I'm clueless about PHP.

PHP hasn't been terrible to work in and I've always been interested in venturing out of closed systems like .NET, but I'm not sure that my experience is colored by my current job (it's pretty bad) or if it will continue to in the next PHP job. Hell, I'm not even sure if my PHP experience is even good enough for another PHP job.

Edit: Located in East Coast, USA.


r/PHPhelp • • May 26 '20

Is there any website like CodePen but for PHP?

9 Upvotes

Hi

I really like CodePen but I can't write in PHP in it. Is there any website similar to it but allows PHP?

Thanks


r/PHPhelp • • May 19 '20

Here is a tutorial to get your started using PHP in the cloud with Digital Ocean or AWS.

9 Upvotes

I know a lot of developers are still using traditional hosting (shared hosting, dedicated, etc..) But there are some real good offerings from Digital Ocean and AWS to take you application to the cloud using tools like droplets or EC2. Here a small tutorial I typed up to get you stared developing PHP in cloud. https://phpnibbles.com/how-to-configure-your-digital-ocean-droplet-or-aws-ec2-instance-for-php-development/


r/PHPhelp • • May 16 '20

I created a tutorial php blog to help new php developers.

9 Upvotes

Let me know if there is anything you would like me to cover. https://phpnibbles.com/

Its pretty new so I only have two posts but will be doing more and more tutorials and explainer posts. I am going to cover things like setting up a proper dev environment for php in cloud using services like aws and digitalocean.


r/PHPhelp • • Apr 08 '20

I would like to make a simple chat system. Right now I have done it with PHP, MySQL and Ajax. But I don't want the chatbox to keep refreshing every second. I want it to refresh only if I sent a message or the other person has sent a message.

9 Upvotes

I have spent a decent amount of time on creating my own online platform and it's all based on PHP and MySQL. I want to integrate a chat system, so it also works with the same user Id's and Sessions as the rest of my site.

I have found socket.io but you need Node installed for it. I have little knowledge about Node. Is it installed on most webhosting servers? Can I just use a combination of socket, node and php? Is that a viable way to make a chat system? I have pretty much written all the chat logic already in PHP and Ajax. Users can send messages to other users. It's just the Ajax refreshing loop that is the problem. I don't want the chatbox to refresh every second and get the data from the database every second, because it's not good for the bandwidth.


r/PHPhelp • • Dec 19 '19

preg_replace with German umlaut

9 Upvotes

Hi, I'm looking for a preg_replace which adds a "+" in front of every word, otherwise my full text search query which I'm getting via a get request does not work.

This is what I have so far:

$products->term = isset($_GET['term']) ? preg_replace('/(\w+)/', '+$1', $_GET['term']) : die();

This works. "keyword1 keyword2" is converted to

+keyword1+keyword2

The problem is that it does not work with German umlaut like ä, ö, ü. So " keywörd1 keyörd2" gives me

+keywö+rd1 +keyö+rd2

as result.

Is there a way to fix this?

Thanks


r/PHPhelp • • Nov 25 '19

Best way to pass JWT token from backend to frontend?

9 Upvotes

Okay so I'm writing a web application (Symfony for backend, some JS framework for frontend, probably Angular). I use JWT tokens for authentication.

When it comes to normal username + password login, it's simple - frontend makes a request with username and password, backend returns token, frontend receives token. This is simple.

But the thing is, I want to allow users to log in using Google or Facebook. I have my backend all set up, but I'm not sure how should I pass the token to frontend.

Because now it's like this:

  1. user clicks a button on frontend

  2. user is redirected to some backend url, which in turn redirects him to a proper Google login url

  3. user logs in and allows my app to use his Google account

  4. user gets redirected by Google to backend url

  5. backend authenticates the user and generates JWT token

And now what's the usual way of passing this token back to frontend? The only thing that comes to my mind is redirecting the user back to frontend with token as query param, like http://example.com/?token=... but this seems insecure.


r/PHPhelp • • Oct 13 '19

INSERT INTO sql table not working.

9 Upvotes

Am I inserting rows into my table correctly? This doesn't work for some reason.

$conn->exec("INSERT INTO Questions_Table (ID, Question, Votes) VALUES ($num_rows, $submitted_question, 1)");

r/PHPhelp • • Feb 13 '19

PHP router works on a local machine but not on a Linux Server.

9 Upvotes

I finished a simple no framework php 7+ website.

It uses a MVC structure and has a router to handle GET, POST, URL change requests.

On the local machine everything works perfectly.

However on the server it looks like the server is blocking the router.

The initial view loads but on url change or post request the following is returned:

Not Found

The requested URL /url was not found on this server.

*Sorry if this is more of a server question. Figured i'd ask here first as i'm sure other's with custom php routers have had this issue before

Fedora 29

Edit:

apache

My file structure is roughly

index.php

-core

--router

-pages

--page1

--page2

--page3

I think the issue is Apache is only able to serve pages in the top level of the var/www/html folder. Best way to fix?


r/PHPhelp • • Jan 17 '19

Constructor, when to choose public vs protected vs private?

9 Upvotes

I'm new to PHP, coming from JavaScript. I've done some stuff with the JavaScript constructor, however, these visibility statements are not used there.

I also have a basic knowledge of what the differences between them are, but can't figure out why you would like to use private or protected.

So could anyone explain (maybe with an higher abstract level example) when to choose what, without explaining again what the differences are?


r/PHPhelp • • Dec 13 '18

Create a Phone Book using Javascript, PHP and SQL.

9 Upvotes

I took some time to create a phone book that utilizes the majority of the three languages above. Decided to do this for practice and it turned out really well.

Github Phone_book Repository


r/PHPhelp • • Dec 10 '18

[Advice, no code]OOP PHP job interview

9 Upvotes

Hey, i hope this is the right subreddit to post my question.

So tomorrow i've got a second meeting with the owner of a small company (3 employees + boss) that makes modules for online stores using Magento.

The first interview went smooth they asked me basic questions to see if i actually was a programmer such as "Can you tell us the difference between a foreach and a for loop?" and "what is the difference between public, private and protected classes?".

Since i'm not doing any "fake it 'till you make it" applying to this job, these were obviously easy questions and i got planned in for a second meeting.

He told me i would speak to their best programmer who would ask me more in depth questions to see if i was up for the task or not.

Even though i'm confident in my PHP, MySQL and JSON/ XML skills, this is really getting me more worried than it should, as such i was wondering if any of you guys who are employed in the field know what kind of questions i should expect?

TL;DR

If you were going to hire a "Junior PHP developer", what type of questions would you ask them to test their knowledge?


r/PHPhelp • • Nov 26 '18

When using a WHILE loop, is there a way to avoid, or mitigate, infinite loops?

9 Upvotes

Hi all. I was using a while loop and accidentally created an infinite loop a few times. Of course I'll be careful in the future. But as a safety measure, are there any built-in tools that can help me avoid infinite loops, or break out of them if they occur? Or would I always have to implement something like that manually (as I ended up doing)?


r/PHPhelp • • May 30 '18

PHP Dependency Injection tutorials?

9 Upvotes

I need a tutorial on using Dependency Injection/IOC in PHP. We are going to build an API and want the output formatters to be "pluggable" meaning we may use DI to accomplish this. I don't know how to do DI in PHP and need some brushing up on it.