Questions tagged [oop]

Object-oriented programming is a powerful software development approach that utilizes "objects" as fundamental building blocks. These objects combine data fields and methods, fostering seamless interactions within their encapsulation.

Exposing the secrets of the Ajax module

Here is the code snippet I am working with: my.data = function () { var getAuth = function (userName, password) { var model = JSON.stringify({ "UserName": userName, "Password": password }); var result; $.ajax({ url: m ...

Object-Oriented Programming and PHP Execution Time

Recently diving into OOP and PHP, I've been trying to stick to the OOP Approach by creating a class for each key feature of my project. So far, it's been working out well. However, I started contemplating about compilation and runtime. If I create a robu ...

PHP Chaining... It's so confusing to me!

I am experimenting with creating a chaining function to manipulate strings retrieved from an XML file. A single original string might require multiple replacements, some sourced from the XML file. Here is the conventional and messy wrapped approach: str ...

Retrieve the property of a class while inside another class that was instantiated within the original class in PHP

Explaining this using the correct terms can be challenging, so maybe an example would be more effective... $main = new MainClass(); $main->performAction(); class MainClass { var $x; var $y; var $z; var $eventProcessor; function ...

In PHP, when declaring properties, you can only use arrays as values. Any other expressions that could be evaluated during compilation are not allowed

While delving into object-oriented programming in PHP, I came across an intriguing feature where property declaration can accept an array as a value. This was mentioned in the PHP documentation. class Test{ public $var7 = array(true, false); } In t ...

Is it possible to pass a JavaScript array to a local variable by reference?

Within my namespace, I have an array defined in JavaScript like this: app.collection.box = []; Additionally, there is a function within the same namespace structured as follows: app.init = function () { var box = this.collection.box; // ... code ...

PHP construction does not seem to be functioning properly as it is displaying a blank page

I have created a PHP class file, but when I try to run it, it does not work. class User { public function __construct(){ $host_name='localhost'; $username='root'; $password=''; $database_name='php&apos ...

The variable is unable to be accessed within the PHP function query

After passing a variable through ajax to a function within my php file "Cart_code.php", I encountered an issue where the variable was not accessible inside the function. Can you help me figure out why? Javascript $.ajax({ type: "POST", url: "incl ...

issue with accessing global variable within class block

While the Python code within the 'outer' function runs smoothly on its own, placing it inside a class seems to cause issues that are difficult for me to comprehend. (I am aware that I could simply pass data as a variable inside the function or d ...

Issue with call function not operating consistently across all subclasses

I am experimenting with using the __call function for pre-action instructions. The issue I am facing is that the __call function only works once, but I need it to be triggered every time the run() method is called. When I call $second_child->run() ins ...

When defining a class property in TypeScript, you can make it optional by not providing

Is there a way to make a property on a Class optional without it being undefined? In the following example, note that the Class constructor takes a type of itself (this is intentional) class Test { foo: number; bar: string; baz?: string; construc ...

Identify the specific namespace from which the function was invoked

Is there a way to identify the current namespace when calling a function? Here's an example: <?php namespace SiteAction; function add ($hook, $function) { /** * I want to determine the namespace from which this function was called * __NA ...

Mastering Dependency Injection for League Flysystem Integration

The goal is to develop a unique Reader class that functions as a wrapper for the League Flysystem documentation The purpose of the Reader is to provide a convenient way of reading all files in a directory, regardless of their physical form (local file or ...

Generating PHP objects at runtime using a string-based approach

Is there a way to create an object in PHP based on a type specified by a string stored in a MySQL database? The table contains columns and sample data like: id | type | propertyVal ----+------+------------- 1 | foo | lorum 2 | bar | ipsum ...and I ...

Understanding the optimal scenarios for utilizing static functions within your codebase

One of my colleagues argues that static is beneficial when performing tasks that do not require any extensions, but we faced a problem when we needed to add a new feature on top of his code. We ended up having to extensively modify the original code becaus ...

I am encountering an error in my PHP code that I am having trouble figuring out how to fix

class Logging{ private $log_file = 'c:/xampp/htdocs/jcert2/tmp/sslogfile.txt'; public static $fp = null; public static function lwrite($message){ if (Logging::fp) Logging::lopen(); // $script_name = pathinfo($_SE ...

Can you explain the concept of a factory function to me?

As I delve into learning Javascript, I have encountered terms like factory functions and constructor functions in the realm of object-oriented programming. Despite my attempts to grasp the distinction between them, I still find myself struggling to fully ...

Assigning objects in PHP

As a PHP learner, I am seeking assistance with the following PHP Object-Oriented Programming (OOP) code: class x{} $x = new x; $x->name = "Chandan"; class y extends x {} // Inheritance $y = new y; var_dump($x); // object X; Shows Name property va ...

Working with dynamic array sizes in methods and setters in PHP

I am relatively new to PHP and have been researching extensively, but I am struggling to find a solution to my current issue. My problem revolves around using setters in a class when dealing with an array of unknown size. For example: class Shirt { ...

What is the most effective approach to designing a database architecture for parallel computing using PHP?

I am currently in the process of creating a tool that is responsible for connecting to various nodes and retrieving their connection data using PHP. The approach I have taken involves implementing a Worker that forks itself in the constructor multiple tim ...

Utilizing AJAX to define the attributes of an object

As a beginner in OOP, I am trying to create an object using an ajax request. My goal is to retrieve 'responseArray' in JSON format and then manipulate it. function address(adres) { this.address_string = adres; var self = this; $.ajax({ typ ...

The base class is invoking a function from its child class

There are two classes, a base class and a derived one, each with an init function. When constructing the derived class, it should: Call its base constructor which: 1.1. Calls its init function Call its own (derived) init function. The issue is that ...

How can you dynamically create a PHP class instance with changing arguments on the fly?

I have a situation where I need to create an instance of a class dynamically by using a variable value. Here is the code snippet: $instance = new $myClass(); My problem arises from the fact that the constructor of the class requires different numbers of ...

Utilize Node.js to parse JSON data and append new nodes to the final output

When parsing a JSON object in Node.js, the resulting hierarchical object can be seen in the debugger: datap = object account1 = object name = "A" type = "1" account2 = object name = "B" type = "2" If we want to add ...

Issues with Python class constructor inheritance: Seeking guidance on correct implementation

I encountered an issue with my Python OOP program that involves two classes, Flan and Outil, inheriting from a superclass called Part. When I call Flan, everything functions perfectly, but when I call Outil, the program fails without any error messages. ...

Class not found error encountered while trying to extend another class

In a directory called "classes," there are two files. The first file is the main class named "Database" which is used to connect to the database. The second file is named "Branch" and it extends the Database class, designed to retrieve data from the databa ...

PHP and MySQL: Difficulty in understanding code for finding properties of a new object

I am new to coding and I am struggling to grasp the script that sets properties for a new object. Can someone please assist me? Thank you in advance. Starting with sign_up.php, I have an input element using the POST method like this... <?php include_ ...

Using the PHP Scope Resolution Operator results in an undefined class constant

Trying to utilize PHP's scope resolution operator to access the bar() method without creating an instance of the Foo class: <?php class Foo { public function bar() { return 'bar'; } } echo Foo::bar; Encountering this e ...

OpenSSL is reporting an SSL Error: Exceeding the maximum number of open files

What could be the issue? Error message File "/usr/lib/python3/dist-packages/OpenSSL/_util.py", line 54, in exception_ from_error_queue raise exception_type(errors) OpenSSL.SSL.Error: [('system library', 'fopen', 'Too many open files'), ('BIO ...

Inheritance and Method Overriding in PHP Objects

Recently, I have been working on some PHP code within the CodeIgniter framework. I have created my own Model class which extends and overrides the default CodeIgniter model. Below is the implementation: <?php class MY_Model extends CI_Model { publi ...

Create a fresh instance of an object in node.js by utilizing the require/new method

I am encountering a beginner problem with node.js where I cannot seem to create objects using the 'new' operator in the index.js file. My goal is to define a simple Person object within a Person.js file, located in the same directory as my index ...

Exploring the world of TypeScript interfaces and their uses with dynamic keys

I am hopeful that this can be achieved. The requirement is quite simple - I have 2 different types. type Numbers: Number[]; type Name: string; Let's assume they are representing data retrieved from somewhere: // the first provider sends data in th ...

Debugging with PHP Decorators

After reading an informative article and going through the Decorator example, I encountered an issue. The code is displaying <strong></strong> instead of the expected <strong><a href="logout.php">Logout</a></strong>. cl ...

Creating custom events in a JavaScript constructor function

Just beginning to learn JavaScript. I have a custom function that I want to assign events to in the constructor. var myFunction = function(){ /* some code */ } myFunction.prototype.add=function(){ /* adding item*/ } Now I am looking to add an event to ...

Using Typescript: invoking static functions within a constructor

This is an illustration of my class containing the relevant methods. class Example { constructor(info) { // calling validateInfo(info) } static validateInfo(info):void { // validation of info } I aim to invoke validateInfo ...

Does writing JavaScript code that is easier to understand make it run slower?

While browsing the web, I stumbled upon this neat JavaScript program (found on Khan Academy) created by another user: /*vars*/ frameRate(0); var Sz=100; var particles=1000; scale(400/Sz); var points=[[floor(Sz/2),floor(Sz/2),false]]; for(var i=0;i<part ...

Using a user-defined object as a specified parameter type in Python functions

After defining my `Player` class in Python3, I found myself struggling to create a method in another class that specifically takes an object of type `Player` as a parameter. Here is what my code looks like: def change_player_activity(self, player: Player) ...

Error catcher

I'm working on developing an exception handler that needs to deal with five different types of exceptions, which I'll refer to as Ex1, Ex2, Ex3, and so on. My initial thought was to create a single class called ExHandler and instantiate it like ...

Utilize an unspecified quantity of variables to store the results generated by a function

I am trying to use a method called __some_method. This method can return one parameter, two parameters, or any number of parameters. I need to call this method from another one and assign the returns to variables dynamically based on the number of returned ...

invoking object-oriented PHP method through AJAX

I have a PHP file with OOP and I want to call one of the functions using AJAX. I have done a lot of research on this (mostly on Stack Overflow), but for some reason, it's not working. I can confirm that the AJAX function is being called (I added an alert ...

In relation to the characteristics of a specific example

class EmployeeInformation(): def __init__(self, first_name, last_name): self.f = first_name self.l = last_name # Just a simple check self.full = self.f + ' ' + self.l employee = EmployeeInformation('John', 'Doe') emplo ...

Struggling to delete event listeners in TypeScript using object-oriented programming with JavaScript

After researching the issue, I have discovered that the onMouseUp event is being fired but it is not removing the EventListeners. Many individuals facing a similar problem fail to remove the same function they added initially. Upon reading information fr ...

Exploring the variances between a Data Access layer and a Database Abstraction Layer, along with optimizing the Database class

Question: What is the difference between Data Abstraction Layer & Data Acess Layer? After reading an interesting article on nettuts, I found myself wondering about the discrepancies between a Data Access Layer and a Database Abstraction Layer. I ...

Exploring OOP Strategies within the Angular MVC Framework!

After coming across a question on Stack Overflow that was similar to mine, I realized I have a lot to learn about Object-Oriented Programming (OOP). Up until now, my coding experience has been mainly procedural. Before diving into my question, let me provi ...

Exploring the Prototype-based programming concept in JavaScript

I am determined to deepen my understanding of JavaScript and explore what lies beneath its surface. While I have delved into various guides on the Object-Oriented Paradigm with Prototypes in JavaScript, I am struggling to comprehend how this paradigm diffe ...

Encapsulating the React Material-ui Datepicker and Timepicker OnChange event callback functionging

I'm new to React and currently incorporating Material-UI into my project for additional UI components. I've noticed some repetitive code that I'm finding difficult to refactor due to constraints within a Material-UI component's implementation. Below is th ...

Different approach to iterating through elements

Looking to implement .forEach instead of a traditional for loop? 'use strict'; var score = (function(){ function updateScore() { for(var i = 0; i < arguments.length; i++) { this.score += arguments[i]; ...

Is there a way to preserve a $this pointer between two classes within separate scripts?

Well, this is a rather interesting scenario: Currently, I am immersed in the world of MVC architecture. There's a User class designated as a library (User.php). Additionally, there's a controller class responsible for managing user input (cont ...

Alternative solution to avoid conflicts with variable names in JavaScript, besides using an iframe

I am currently using the Classy library for object-oriented programming in JavaScript. In my code, I have implemented a class that handles canvas operations on a specific DIV element. However, due to some difficulties in certain parts of the code, I had t ...

Utilizing the principles of object orientation in Javascript to enhance event management

After attempting to modularize my JavaScript and make it object oriented, I found myself struggling when dealing with components that have multiple instances. This is an example of how my code currently looks: The HTML file structure is as follows: & ...

JavaScript OOP Function call not functioning in IE9

When using IE9, a JavaScript OOP Function call does not seem to work for me. Here is my code snippet: var newobj = new SAObject(); <input onclick="newobj.function()" /> Upon clicking the button, nothing happens. No alert is displayed, and it seem ...

"Assigning an array as a value to an object key when detecting duplicates in a

Let's assume the table I'm iterating through looks like this: https://i.stack.imgur.com/HAPrJ.png I want to convert each unique value in the second column into an object, where one of the keys will hold all values from corresponding rows. Here's what I h ...

Tips for incorporating nested generics in Typescript

Currently, I am developing a straightforward activity execution framework that allows developers to define activities which can be executed within a workflow. To enhance type safety and boost developer productivity by utilizing type hints, I aim to incorp ...

How to Change a Property in a Child DTO Class in NestJS with Node.js

I am working with enums for status: export enum Status { Active = "Active", Inactive = "Inactive", } Additionally, I have a UserStatus enum: export enum UserStatus { Active = Status.Active, }; There is also a common dto that inc ...

What is the best way to eliminate the "driver" instance from the test classes?

Can someone assist me with this question: I am seeking guidance on how to eliminate the instance driver from the BaseTest class while still being able to utilize it in the class and its subclasses? I am currently using POM to construct a testing-framewor ...

PHP: Parameterizing Methods with Inheritance

Imagine that I have a PHP Class: class MyClass { public function doSomething() { // perform an action } } Now, let's say I derive from this class and override the doSomething method: class MyOtherClass extends MyClass { public function doS ...

JavaScript Memoization: Enhancing Performance Through Caching

Recently, I delved into various JavaScript design patterns and stumbled upon memoization. While it seems like an effective way to prevent redundant value calculations, I can't help but notice a flaw in its implementation. Consider the following code s ...

What is the process for converting an attribute ArrayList<String>, ArrayList<Integer>, or ArrayList<MYCLASS> from a JSON object into a Java object?

Being a novice in programming, I am currently attempting to save my objects as JSON in a text file. However, I have encountered difficulties when passing the JSON object to my constructor. Here is the structure of my 'Aluno' class: public class ...

Assist with correcting pagination class

Presented here is my pagination class. The data within the construct is referring to another class that handles database queries and other functionalities. However, I am encountering an issue where I cannot seem to align the data output with the pagination ...

What is the best way to extract a session variable from a class in PHP?

Is there a way to access variables outside of the class? ...

Utilizing object-oriented programming to establish a straightforward problem tracking system

In this code snippet, we have dbconnect.class.php: <?php class Connect { public $error; protected $db; public function __construct() { $link = mysql_connect("localhost","root","1") or $this->error = mysql_error() ...

Creating a new object within a class in Symfony using PHP: How can I instantiate an object from another class?

I created a PHP Symfony project to enhance my understanding of the framework. However, I have encountered a problem where I need to access another Controller within my current Controller in order to utilize its methods. In simpler terms: How can I instant ...

The inheritance caused this scope to be lost

Here is an illustration of code with two files and "classes". In the CRUD class, there is a problem with this.modelName when setting routes as it changes the context. The question arises on how to maintain the same scope within the CRUD where modelName is ...

Python inheritance and the issue of default values being overridden

Currently experimenting with inheritance in Python and encountering an issue where a field labeled famil gets overwritten by the previous instance's input when no value is provided for famil. class Person: def __init__(self, famil=[], name="Jim"): ...

How can two classes be extended in PHP using OOP?

As a beginner in OOP, I am currently working on writing a PHP class to establish a connection with an FTP server. class ftpConnect { private $server; private $user; private $password; private $connection_id; private $connection_correct = false; ...

Inheritance of a Class Dealing with Empty Values - Object-Oriented

I have a well-structured class that I use for all my user-related methods: class User { protected $_db, $_data; public function __construct($user = null, $findby = 'id') { $this->_db = DB::getInstance(); if (!$user) ...

What is the reason for the num.is_integer() function returning false?

class Item: pay_rate = 0.8 # The pay after %20 discount all = [] def __init__(self, name: str, price: float, quantity=0): #Run validations to the recieved arguments assert price >= 0, f"Price {price} is not greater than ...

"Exploring the concepts of object inheritance and utilizing nested commands

Seeking help with nested console menus and object sharing: Here's a simplified scenario: import cmd class MainConsole(cmd.Cmd): def __init__(self,obj1,obj2): cmd.Cmd.__init__(self) self.prompt = ">" self.obj1 = obj1 # ...

Optimal approach for designing interfaces

I have a situation where I have an object retrieved from the database, which includes assignee and author ID properties that refer to user objects. As I transform a number into a user object, I am unsure about the best practice for defining the type of the ...

Running function without the need to click on 'li' element

In the process of developing a simple guessing game, my aim is to allow users to click on a number and have that number stored as userAnswer, while the computerAnswer is a randomly generated number between one and ten. Despite setting the setVariables() f ...

Optimal approach for incorporating classes in PHP

When saving a file to be included in another PHP file, what is the recommended practice: should it be saved as myClass.php or myClass.inc? ...

leveraging ajax callbacks, the significance of http status codes and essential validation concepts

Recently, I've been working on a server side AJAX class designed to return a JSON string in response to an AJAX request. One question that has been on my mind is when it would be appropriate to return HTTP status codes based on the server's respo ...

Using a JSON database to implement various user levels in a domain model

Here is the domain model that I believe to be accurate. I am currently attempting to implement this on a JSON database, but I am uncertain if I am headed in the right direction. From my understanding of JSON, there are no inherent relationships between obj ...

Class for managing the connection between MongoDB and PHP

Currently, I am seeking a reliable example of developing a PHP class that can manage connections to multiple MongoDB databases. In my current project, I need to interact with at least five distinct databases. It would be quite resource-intensive if I had t ...

What is the best way to choose which attributes from a class should be incorporated into an UPDATE dynamic query?

Example of a Model Class class Games { public $id = 0; public $date = null; public $player1_id = 0; public $player2_id = 0; public $score = null; public function save(){ if(empty($this->id)){ // perform INSE ...