Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8468075
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T15:49:52+00:00 2026-06-10T15:49:52+00:00

Choices I am learning OOP PHP, but some things are really confusing. I have

  • 0

Choices

I am learning OOP PHP, but some things are really confusing. I have a general idea of where to use static methods, but I’m not sure if here it’s a good idea.

My questions is about which is actually the best approach for the specific problem I am facing (described below). The general guidelines I’ve found online didn’t help for this specific problem. Here is what I thought (from more likely to be correct to less):

  • Extend the Language class, create a single object (that gets the language in the initialization) and call a method with the $id that would return the translated string.

  • Merge both classes into one. The language would be found when initialized and a method called when needed. But it would behave a little as a God object.

  • Make the Language class static. Therefore I would be able to use it from within the Text. I would create a Text instance and call a method with different $id. Similar to using it with globals. There’s almost no other place where I’d need to use the Language class.

  • Extend the Language class with Text, create an object for each translation. This would probably create too much overhead.

  • Not do anything. It’s tempting (don’t fix it if it’s not broken), but I intend to start developing with someone else soon, so clean and clear code is needed.

Code

Now the simple class:

class Language
  {
  public $Lang;
  public function __construct()
    {
    if ( !empty($_POST['lang']) )    // If the user tries to change the language
      {
      $this->Lang = mysql_real_escape_string($_POST['lang']);  // Assign the language to variable.
      $_SESSION['lang'] = $this->Lang;      //Sets the session to have that language.
      if ($_SESSION['logged']==1)          // If user is logged
        {
        $User=$_SESSION['user'];
        mysql_query("UPDATE users SET lang='$this->Lang' WHERE email='$User'") or die(mysql_error());  // Saves the language into user preferences
        }
      }
    else      // If no request is done.
      {
      if ($_SESSION['logged']==1)    // DO. Check for user's language
        {
        $User=mysql_real_escape_string($_SESSION['user']);
        $result=mysql_query("SELECT * FROM users WHERE email='$User'");
        $row=mysql_fetch_array($result);
        $this->Lang=$row['lang'];
        }
      else
        if ( !empty ($_SESSION['lang']))  // If the session exists (not empty)
          $this->Lang = $_SESSION['lang'];  // Assign the session language to variable.
        else          // If it doesn't exist
          $this->Lang = substr ($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);  // Get it from the browser
      }
    //If the language is not supported (or still doesn't exist), then put "en" as default. Supported so far: en, es.
    if ( $this->Lang !== "en" && $this->Lang !== "es") $this->Lang="en";
    }
  }

I have few methods inside this class, but that’s the only relevan code here. So I initialize it with $Language=new Language; and then use $Language->Lang; to obtain the user language. So far so good.

This is the function I want to reconvert to a class. It gets an integer or a string, searches it as an id with mysql and returns a translated string in the right language. Now, how do I achieve this? Here it’s the text() function. It was used with globals, which is apparently a really bad practice.

function text($Id)
    {
    // Already defined and tested that are valid (sql injection avoided also)
    global $Lang;
    global $Url;
    global $Version;
    global $Banner;
    if (!empty($Url["folder"])) $FullUrl = "/".$Url["folder"]."/";
      else $FullUrl="/";
    if (!is_int($Id)) $Id = mysql_real_escape_string( $Id );

    $numargs = func_num_args();  // Get the number of arguments that are being passed.
    if ($numargs == 2)  // If there are actually two
      $Var=func_get_arg(1);  // Set $Var with the second value (1).

    if (is_int($Id))  // If a number is being passed
      {
        // Add AND page='$FullUrl' to control scope of the strings translated
      $results = mysql_query("SELECT * FROM translations WHERE id='$Id'") or die ('Could not query:' . mysql_error());
      $row = mysql_fetch_assoc($results);
      if (!empty($row[$Lang]) && !isset($Var)) echo stripslashes($row[$Lang]);  // If there is some, echo it
        elseif ($Var==1) return stripslashes($row[$Lang]); // If it is required to be a returned string, send it.
      else error($FullUrl,$Lang);  // If there is nothing there, calls error function.
      }
    else  // If a string is being passed
      {
      $results = mysql_query("SELECT * FROM htranslations WHERE keyword='$Id'") or die ('Could not query:' . mysql_error());
      $row = mysql_fetch_assoc($results);

      if (!empty($row[$Lang]) && !isset($Var)) echo stripslashes($row[$Lang]);  // If it exists in the table, echo it
      elseif (!empty($row[$Lang]) && isset($Var)) return stripslashes($row[$Lang]);
      else  // Else (it doesn't exist)
        {
        $Id = str_replace("_", " ", $Id);  // Replace the "_" with " "
        if (!isset($Var))
          {
          echo $Id;  // Echo the passed string with spaces
          }
        else return $Id;

        $Banner="There might be some misstranslation. Please report if needed.";
        }
      }
    }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T15:49:54+00:00Added an answer on June 10, 2026 at 3:49 pm

    So the text function has lots of side effects; meaning, it’s touching a lot of
    stuff, and sometimes returning and other times printing stuff to
    standard output. This is usually not good because it is hard to debug, unit-test
    and refactor

    I would go with option 2: Merge both classes into one. The language would be found
    when initialized and a method called when needed.

    Below is how I would implement this (I kept as much code intact as possible so you could understand
    what was changed in regards to OOP. There are many other things I would change; mostly what others
    have already commented on plus not printing anything from within the method. It’s good practice
    to have methods return something and not modify the application state from within

    Things I changed:

    The text function was actually changing a global variable ($Banner) during certain
    times, using two global variables ($Url) and ($Lang which is actually from the language
    object) and then returning an Id from the database or possibly printing to
    standard output.

    Since moving the text function into the Language class, I converted the global $Lang
    variable to use the instance variable $Lang of the Language class

    The $Url method is only being used in the text function and thus, can be passed into the text method

    The global variable $Banner is actually being set by the text function which I consider a bad
    side effect. I decided to replace this code:

    $Banner = “There might be some misstranslation. Please report if needed.”;

    with

    return false.

    This way, if the text method returns false, you can set the $Banner
    variable to “There might be some mistranslation. Please report if needed.” which
    is done from outside of the object.

    Also, I removed the global variable $Version from the text function becaue it was not used within
    the function

    I would also recommend working on having the text method only return and not print to the
    standard output. Misstranslation is spelt wrong. It should be mistranslation.

    I hope this helps…

    <?php
    
    class Language {
    
        public $Lang;
    
        public function __construct() {
            if (!empty($_POST['lang'])) {    // If the user tries to change the language
                $this->Lang = mysql_real_escape_string($_POST['lang']);  // Assign the language to variable.
                $_SESSION['lang'] = $this->Lang;      //Sets the session to have that language.
                if ($_SESSION['logged'] == 1) {          // If user is logged
                    $User = $_SESSION['user'];
                    mysql_query("UPDATE users SET lang='$this->Lang' WHERE email='$User'") or die(mysql_error());  // Saves the language into user preferences
                }
            } else {      // If no request is done.
                if ($_SESSION['logged'] == 1) {    // DO. Check for user's language
                    $User = mysql_real_escape_string($_SESSION['user']);
                    $result = mysql_query("SELECT * FROM users WHERE email='$User'");
                    $row = mysql_fetch_array($result);
                    $this->Lang = $row['lang'];
                } else
                if (!empty($_SESSION['lang']))  // If the session exists (not empty)
                    $this->Lang = $_SESSION['lang'];  // Assign the session language to variable.
                else          // If it doesn't exist
                    $this->Lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);  // Get it from the browser
            }
            //If the language is not supported (or still doesn't exist), then put "en" as default. Supported so far: en, es.
            if ($this->Lang !== "en" && $this->Lang !== "es")
                $this->Lang = "en";
        }
    
        public function text($Id, $Url) {
            // Already defined and tested that are valid (sql injection avoided also)
            if (!empty($Url["folder"]))
                $FullUrl = "/" . $Url["folder"] . "/";
            else
                $FullUrl = "/";
            if (!is_int($Id))
                $Id = mysql_real_escape_string($Id);
    
            $numargs = func_num_args();  // Get the number of arguments that are being passed.
            if ($numargs == 2)  // If there are actually two
                $Var = func_get_arg(1);  // Set $Var with the second value (1).
    
            if (is_int($Id)) {  // If a number is being passed
                // Add AND page='$FullUrl' to control scope of the strings translated
                $results = mysql_query("SELECT * FROM translations WHERE id='$Id'") or die('Could not query:' . mysql_error());
                $row = mysql_fetch_assoc($results);
                if (!empty($row[$this->Lang]) && !isset($Var)) {
                    echo stripslashes($row[$this->Lang]);  // If there is some, echo it
                } elseif ($Var == 1) {
                    return stripslashes($row[$this->Lang]); // If it is required to be a returned string, send it.
                } else {
                    error($FullUrl, $this->Lang);  // If there is nothing there, calls error function.
                }
            } else {  // If a string is being passed
                $results = mysql_query("SELECT * FROM htranslations WHERE keyword='$Id'") or die('Could not query:' . mysql_error());
                $row = mysql_fetch_assoc($results);
    
                if (!empty($row[$this->Lang]) && !isset($Var)) {
                    echo stripslashes($row[$this->Lang]);  // If it exists in the table, echo it
                } elseif (!empty($row[$this->Lang]) && isset($Var)) {
                    return stripslashes($row[$this->Lang]);
                } else {  // Else (it doesn't exist)
                    $Id = str_replace("_", " ", $Id);  // Replace the "_" with " "
                    if (!isset($Var)) {
                        echo $Id;  // Echo the passed string with spaces
                    } else {
                        return $Id;
                    }
    
                    return false;
                }
            }
        }
    
    }
    
    ?>
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm currently learning Django and some of my models have custom methods to get
I am learning MVC 3 and I have not found people using some logic
I really have no idea how to approach this. I've been reading for like
Say I have choices defined as follows: choices = (('1','a'), ('2','b'), ('3','c')) And a
We have several choices for logging in our .NET (C#) server application. We are
When Using UIPickerController I have two choices on my App: take a picture take
I want to have multiple multiple choices given to user after the form submit
I am learning scheme. I know how to use both lambda and let expressions.
I am learning ajax with php. And know how to do GET/POST and pass
I am learning C and wish to create 2D static objects, line graphs etc

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.